我将所有网站 HTML 存储在一个 javascript 字符串中,我想将它放在一个 iframe 中。 如何将该 HTML 字符串放入 iframe 并使其显示网站?我试过 this.src = HTML_STR; this.innerHTML = HTML_STR;但它们不显示 HTML_STR。
我知道这可能很愚蠢,因为我可以将 iframe src 设置为网站并以这种方式显示网站,而不是将网站 HTML 放在字符串中。
但是 我这样做的原因是因为它是一个网站更新程序。所以我想获取网站(我正在更新)HTML,将所有具有“可更新”类的元素转换为文本区域(以便它们可以更新),然后在 iframe 中显示该 HTML。
使用 iframe 而不仅仅是将 HTML 放入 div 的另一个原因是因为每个网站都导入一个 .css 样式表并且我不希望他们的 css 文件影响我的更新程序网站 css 或者让我的更新程序.css 会影响网站的 HTML 外观,因此如果我在 iframe 中显示网站,每个网站的 css 不会相互影响。
例如,如果 updater.css 具有以下内容,它将影响其他网站 html 中的所有 p 元素:
p { background-color: red; width: 50%; }
那么有没有办法将我自己的 HTML 插入到 iframe 中。或者是否有另一种方法来实现我想要做的事情。
最佳答案
假设您想从父级写入 iframe,您可以这样做:
var ifrm = document.getElementById('myFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();
这是 a working jsFiddle .原始代码取自 here和 here .
关于javascript - 可能的 : Insert my own HTML(whole website) into an iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7528504/