最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - scroll an iframe from parent page - Stack Overflow

programmeradmin8浏览0评论

I have created two webpages, one contains the other in an iframe. I would like to scroll the embedded page from the parent page via 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>
<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.

How do I scroll the iframe to a certain position?

I have created two webpages, one contains the other in an iframe. I would like to scroll the embedded page from the parent page via 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>
<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.

How do I scroll the iframe to a certain position?

Share Improve this question edited Feb 5, 2014 at 15:09 aksu 5,2355 gold badges25 silver badges39 bronze badges asked May 29, 2013 at 19:48 stackErrstackErr 4,1704 gold badges27 silver badges49 bronze badges 2
  • Do you know the content of "go.html"? can u simple focus on a required element within it? – Yuriy Galanter Commented May 29, 2013 at 19:53
  • @YuriyGalanter I do know the contents of go.html but it contains another iframe on another domain so I cant access it. I did the iframe in an iframe to get around the same origin policy. – stackErr Commented May 29, 2013 at 19:55
Add a comment  | 

2 Answers 2

Reset to default 9

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.

Update 2 This works universally:

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

You have to wait for iframe content to finish loading for scrollTo to work.

You can use window.postMessage to send a message from your parent frame to the iframe, telling it to scroll. This takes you setting-up a postMessage script in the parent frame and a receiveMessage script in the iframe. It's the receiveMessage code that would actually scroll the iframe.

I've used this polyfill quite successfully: http://benalman.com/projects/jquery-postmessage-plugin/

发布评论

评论列表(0)

  1. 暂无评论