var cssLink = document.createElement("link")cssLink.href = "pFstylesEditor.css";cssLink.rel = "stylesheet";cssLink.type = "text/css";
//Instead of this//frames['frame1'].document.body.appendChild(cssLink);//Do this
var doc=document.getElementById("edit").contentWindow.document;
//If you are doing any dynamic writing do that firstdoc.open();doc.write(myData);doc.close();
//Then append childdoc.body.appendChild(cssLink);
var cssFile = document.createElement("link")cssFile.rel = "stylesheet";cssFile.type = "text/css";cssFile.href = "iFramePage.css";
然后将该CSS文件设置为受尊重的iFrame部分
//to Load in the Body Partframes['my_iFrame'].document.body.appendChild(cssFile);//to Load in the Head Partframes['my_iFrame'].document.head.appendChild(cssFile);
在这里,您也可以使用这种方式在iFrame中编辑页面的头部
var $iFrameHead = $("#my_iFrame").contents().find("head");$iFrameHead.append($("<link/>",{rel: "stylesheet",href: urlPath,type: "text/css" }));
/*** Creates a messenger between two windows* which have two different domains*/class CrossMessenger {
/**** @param {object} otherWindow - window object of the other* @param {string} targetDomain - domain of the other window* @param {object} eventHandlers - all the event names and handlers*/constructor(otherWindow, targetDomain, eventHandlers = {}) {this.otherWindow = otherWindow;this.targetDomain = targetDomain;this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));}
post(event, data) {
try {// data obj should have event namevar json = JSON.stringify({event,data});this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}}
receive(e) {var json;try {json = JSON.parse(e.data ? e.data : "{}");} catch (e) {return;}var eventName = json.event,data = json.data;
if (e.origin !== this.targetDomain)return;
if (typeof this.eventHandlers[eventName] === "function")this.eventHandlers[eventName](data);}
}
在两个窗口中使用它进行通信可以解决您的问题。
在主窗口,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\n');msger.post("cssContent", {css: cssContent})
然后,从Ifram接收事件。
在Ifram中:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {cssContent: (data) => {var cssElem = document.createElement("style");cssElem.innerHTML = data.css;document.head.appendChild(cssElem);}})