【问题标题】:scroll an iframe from parent page从父页面滚动 iframe
【发布时间】:2016-05-02 23:59:07
【问题描述】:

我创建了两个网页,一个在 iframe 中包含另一个。我想通过javascript从父页面滚动嵌入页面。

到目前为止我所尝试的:

  1. $('#go').scrollTop(200);

  2. $('.footer').scrollTop(200);

  3. var frame = document.getElementById('go');
    frame.contentWindow.scrollTo(0, 200);

这些都不起作用

父网页html:

<html>
<body>
.
.
.
<div class="footer">
        <iframe id="go" src="go.html"></iframe>
    </div>
     </body>
</html>

这两个网页都是计算机上的本地文件,我正在使用带有“--allow-file-access-from-files”标志的 Google chrome。

如何将 iframe 滚动到某个位置?

【问题讨论】:

  • 你知道“go.html”的内容吗?您可以简单地关注其中的必需元素吗?
  • @YuriyGalanter 我知道 go.html 的内容,但它包含另一个域上的另一个 iframe,所以我无法访问它。我在 iframe 中做了 iframe 以绕过相同的来源政策。

标签: javascript jquery


【解决方案1】:

这行得通:

document.getElementById("go").contentWindow.setTimeout("this.scrollTo(0, 200);",1);

更新。多哈。仅适用于 IE,但我认为那里有一些东西。

更新 2 这普遍适用:

document.getElementById("go").onload = function () { this.contentWindow.scrollTo(0, 200) };

您必须等待 iframe 内容完成加载才能让 scrollTo 工作。

【讨论】:

  • 是的,在 Chrome 中不起作用!!而且我还尝试了 SetTimeout 的几种变体,但都没有运气:(。
  • 更新解决方案,请试一试。
【解决方案2】:

您可以使用window.postMessage 将消息从您的父框架发送到 iframe,告诉它滚动。这需要您在父框架中设置postMessage 脚本,并在 iframe 中设置receiveMessage 脚本。实际上会滚动 iframe 的是 receiveMessage 代码。

我已经非常成功地使用了这个 polyfill:http://benalman.com/projects/jquery-postmessage-plugin/

【讨论】:

  • Yuriy 提供的解决方案比这更容易实现。感谢插件,以后会派上用场的!
猜你喜欢
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2012-03-23
相关资源
最近更新 更多