【发布时间】:2008-12-18 18:09:56
【问题描述】:
这听起来很奇怪,但这是我试图用 javascript 做的事情(这都是由事件处理程序触发的):
- 将页面的内容(最好是整个文档或至少 documentElement 对象)保存到变量中。
- 创建一个 iframe 并将其插入 身体。
- 将 iframe 的文档替换为保存的文档(这样 iframe 现在与外页的内容相同)。
- 更改外页。
除了替换 iframe 文档的部分外,一切都很花哨。我尝试了很多不同的方法,但都有问题(如下所述)。当页面在 iframe 中时,我需要事件处理程序、样式、链接等才能正常工作。
是的,我意识到我可以将 iframe 的 src 设置为当前页面的 url,但我宁愿页面不必加载。如果我不能想出一个解决方案,这就是我要做的。
我已经尝试过的事情:
var html = iframe.contentWindow.document.importNode(document.documentElement, true);
iframe.contentWindow.documentElement = html;
我收到一条错误消息(“设置只有 getter 的属性”)。
var html = iframe.contentWindow.document.importNode(document.documentElement, true);
var idoc = iframe.contentWindow.document;
while(idoc.firstChild) idoc.removeChild(idoc.firstChild); // remove all children (firefox automatically creates an html element for iframes with no src)
idoc.appendChild(html); // insert a new documentElement
这似乎可行,但不会重新渲染样式,并且事件处理程序也不起作用。有趣的是,链接也不起作用,它们甚至没有使用浏览器的默认样式。也许这是因为 DOCTYPE 没有复制到 iframe 中?
iframe.contentWindow.document.documentElement.innerHTML = document.documentElement.innerHTML;
这与 removeChild/appendChild 方法的行为相同。
似乎如果我可以让浏览器重新呈现样式并重新注册事件处理程序,那么我会很高兴,但我不确定这是否可能。
【问题讨论】:
标签: javascript html iframe