javascript 从父页面滚动 iframe
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16822608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scroll an iframe from parent page
提问by stackErr
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.
我创建了两个网页,一个在 iframe 中包含另一个。我想通过 javascript 从父页面滚动嵌入页面。
What I have tried so far:
到目前为止我尝试过的:
$('#go').scrollTop(200);
$('.footer').scrollTop(200);
var frame = document.getElementById('go');
frame.contentWindow.scrollTo(0, 200);
$('#go').scrollTop(200);
$('.footer').scrollTop(200);
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”标志的谷歌浏览器。
How do I scroll the iframe to a certain position?
如何将 iframe 滚动到某个位置?
采纳答案by Yuriy Galanter
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 2This 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 工作。
回答by Jasper
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.
您可以使用window.postMessage
从父框架向 iframe 发送消息,告诉它滚动。这需要您postMessage
在父框架中设置receiveMessage
脚本并在 iframe 中设置脚本。这是receiveMessage
实际滚动 iframe的代码。
I've used this polyfill quite successfully: http://benalman.com/projects/jquery-postmessage-plugin/
我已经非常成功地使用了这个 polyfill:http: //benalman.com/projects/jquery-postmessage-plugin/