启用 iframe 的设计模式

sam*_*ach 3 html javascript iframe

我有一个 iframe,在 javascript 中我启用了如下设计模式

iframe.contentDocument.designMode="on";
Run Code Online (Sandbox Code Playgroud)

如果我创建我的 iframe 内联,它工作正常。但是,如果我在父页面中加载带有“src”属性的 iframe 并按如下方式打开设计模式:

iframes=document.getElementsByTagName('iframe');
for(iframe in iframes)
{
iframes[iframe].contentDocument.designMode="on";
}
Run Code Online (Sandbox Code Playgroud)

那么它不起作用。如果我加载指定 src 属性的 iframe,如何从容器页面启用 iframe 的设计模式?不是内联!!谢谢

Tim*_*own 6

根据浏览器的不同,有几个潜在的问题:

  • 并非所有浏览器(尤其是旧浏览器)都支持 contentDocument
  • for...in不能保证在 a 上工作NodeList,这是getElementsByTagName()返回的内容。改用for循环。
  • 您可能需要等待所有 iframe 加载完毕。load只有在所有 iframe 加载完毕后,主文档的事件才会触发。

否则,只要 iframe 来自同一个域,就可以designMode从包含文档中设置其文档的属性。以下应该工作:

window.onload = function() {
    var iframes = document.getElementsByTagName('iframe');
    for (var i = 0, len = iframes.length, doc; i < len; ++i) {
        doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
        doc.designMode = "on";
    }
};
Run Code Online (Sandbox Code Playgroud)