简体   繁体   English

从父页面滚动iframe

[英]scroll an iframe from parent page

I have created two webpages, one contains the other in an iframe. 我创建了两个网页,一个包含iframe中的另一个网页。 I would like to scroll the embedded page from the parent page via javascript. 我想通过javascript从父页面滚动嵌入页面。

What I have tried so far: 到目前为止我尝试了什么:

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

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

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

none of these have worked 这些都没有奏效

the parent webpage html: 父网页html:

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

Both of these webpages are local files on the computer and I am using Google chrome with "--allow-file-access-from-files" flag. 这两个网页都是计算机上的本地文件,我使用的是带有“--allow-file-access-from-files”标志的Google Chrome。

How do I scroll the iframe to a certain position? 如何将iframe滚动到某个位置?

This works: 这有效:

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

Update . 更新 Doh. 卫生署。 Works in IE only, but I think there's something there. 仅适用于IE,但我认为那里有一些东西。

Update 2 This works universally: 更新2这普遍适用:

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

You have to wait for iframe content to finish loading for scrollTo to work. 您必须等待iframe内容完成加载才能使scrollTo正常工作。

You can use window.postMessage to send a message from your parent frame to the iframe, telling it to scroll. 您可以使用window.postMessage从父框架向iframe发送消息,告诉它滚动。 This takes you setting-up a postMessage script in the parent frame and a receiveMessage script in the iframe. 这会让您在父框架中设置postMessage脚本,在iframe中设置receiveMessage脚本。 It's the receiveMessage code that would actually scroll the iframe. 这是实际滚动iframe的receiveMessage代码。

I've used this polyfill quite successfully: http://benalman.com/projects/jquery-postmessage-plugin/ 我已经非常成功地使用了这种polyfill: http//benalman.com/projects/jquery-postmessage-plugin/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM