【问题标题】:Static iframe at bottom makes webpage unscrollable底部的静态 iframe 使网页无法滚动
【发布时间】:2013-04-06 09:50:27
【问题描述】:

看看:http://jsfiddle.net/BUNVM/1/

<body>
    This is a test page<br/>
    (many more lines to make the page scrollable)
    This is bottom of the test page<br/>
    <iframe id="bot_frame" style="width:250px;height:240px;position:fixed;bottom:0px;right:0px;text-align:left;border:0;"></iframe>
    <script type="text/javascript">
    var iframe_content = '<!DOCTYPE html><html><body style="background-color:#ddd">Frame content</body></html>';
    window.onload = function() {
        var iframe = document.getElementById("bot_frame");
        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(iframe_content);
        iframe.contentWindow.document.close();
    };
    </script>
</body>

它在屏幕右下角有一个静态 iframe,内容通过 document.open() 和 document.write() 和 document.close() 添加到其中。

当您只打开输出帧时,一切都很好:http://jsfiddle.net/BUNVM/1/show/

但尝试在 Chrome 中访问以“#”结尾的相同输出帧:http://jsfiddle.net/BUNVM/1/show/#

现在尝试滚动页面,页面卡在底部,无法向上/向下滚动。即使拖动滚动条,按键盘上的箭头键也不起作用。但是,如果您将鼠标放在 iframe 上,然后使用鼠标滚轮/pad 滚动,则滚动会起作用。

我只能在 Ubuntu 12.04 的 Chrome v21.0.1180.89 中进行测试。

请注意,上述情况仅在您使用井号“#”重新加载页面时发生(仅向已加载的页面添加“#”不会重新加载页面)。

我想知道造成这种情况的原因和可能的解决方案。

【问题讨论】:

  • 在 Chromium 版本 25.0.1364.160 Ubuntu 12.04 中也可重现
  • 注释掉“iframe.contentWindow.document.close();”行解决了这个问题,但是为什么“close()”会导致问题呢?
  • 更多洞察:将 iframe 样式的 bottom:0px 更改为 top:100px,我们可以将页面从底部滚动到顶部 100px,但不能滚动到上面。此外,只有通过单击拖动滚动条才能进行滚动。显然 iframe document.close() 正在强制重新计算父页面的开始位置。似乎是一个 Chrome 错误。

标签: google-chrome dom iframe


【解决方案1】:

这是之前报道过的chrome中的一个bug:https://code.google.com/p/chromium/issues/detail?id=102816

如果您在将鼠标悬停在 iframe 上时尝试滚动,似乎会使滚动再次起作用。所以我创建了一个小技巧,即使它很丑也应该让它工作:

var offset = document.body.scrollTop || 0;
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(iframe_content);
iframe.contentWindow.document.close();

if(document.location.toString().match(/#(top)?$/)) {
    // Force a scroll on the iframe to make scrolling work again
    iframe.contentWindow.document.body.scrollTop = 0;

    // Scroll back to the original scroll position as document.close will have scrolled to the bottom
    document.body.scrollTop = offset;
}

http://jsfiddle.net/Tsq7N/

http://jsfiddle.net/Tsq7N/show/#

基本上我在 iframe 上伪造了一个滚动条,这使得再次滚动成为可能,之后我将文档的 scrollTop 设置回 document.open/write/close 发生之前的状态。

【讨论】:

  • 我通过在 iframe 中使用 src="javascript:function() { return "";}" 解决了这个问题,而不是打开、写入和关闭。
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 2015-11-23
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2015-07-12
相关资源
最近更新 更多