【问题标题】:behavior of iframe contentDocument in chrome and firefoxchrome 和 firefox 中 iframe contentDocument 的行为
【发布时间】:2013-04-29 04:46:53
【问题描述】:

这是我的 testing.html:

<html>
<meta charset="utf-8">
<script>
window.onload = function() {
    var a = document.getElementById("divid");
    var ifr = document.createElement('iframe');
    a.appendChild(ifr);
    ifr.contentDocument.body.style.cssText = (
      'margin: 0px;' +
      'padding: 0px;' +
      'height: 100%;' +
      'width: 100%;');
}
</script>

<head></head>
<body>
<div id="divid"/>
</body>
</html>

这里 ifr.contentDocument.body.style.cssText = (...) 在 chrome 上可以正常工作,但在 Firefox 上不行。它是Firefox的错误吗?有什么解决办法吗?

找到解决方法: 看起来Firefox中有一个奇怪的种族错误。使用 setTimeout 的以下解决方法将使其正常工作,如下所示:

<html>
<meta charset="utf-8">
<script>
window.onload = function() {
    var a = document.getElementById("divid");
    var ifr = document.createElement('iframe');
    ifr.id = "fid";
    a.appendChild(ifr);
    setTimeout (function() {
        ifr.contentDocument.body.style.cssText = (
        'margin: 0px;' +
        'padding: 0px;' +
        'height: 100%;' +
        'width: 100%;');
    }, 100);
}
</script>

<head></head>
<body>
<div id="divid"/>
</body>
</html>

【问题讨论】:

标签: javascript html google-chrome firefox iframe


【解决方案1】:

试试这个:

 ifr.contentDocument.getElementsByTagName('body')[0].style.cssText = (
  'margin: 0px;' +
  'padding: 0px;' +
  'height: 100%;' +
  'width: 100%;');

还有

<div id="divid"> </div>

【讨论】:

    【解决方案2】:

    当您在 Firefox 中附加 iframe 时,它​​会开始在 iframe 中异步加载 about:blank。然后你触摸文档,所以它必须在其中同步创建一个about:blank 文档,然后你修改它。然后异步加载完成并替换您修改的文档。

    在修改之前等待框架上的加载事件触发。

    【讨论】:

    • 感谢您的解释。有没有办法让firefox不这样做?我可以将 iframe 的 src 属性设置为数据 uri 之类的吗?
    • 它将异步加载数据URI。这里正确的做法是等待加载事件。
    • @BorisZbarsky 如何等待加载事件?
    • 以上代码情况下:ifr.addEventListener("load", function() { /* do things */ });
    猜你喜欢
    • 2016-02-09
    • 2011-09-28
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2014-04-06
    • 2012-01-06
    相关资源
    最近更新 更多