在 iframe 中单击子页面时如何将父页面滚动到顶部?
当有人点击 iframe(子页面)内的链接时,如何让父页面滚动到顶部?问题是子页面将保留在页面的同一位置,因为 iframe 的高度比父页面大很多。
请注意:父页面和子页面位于不同的子域中。
我创建了一个演示来展示这一点: http://www.apus.edu/_test/iframe/index.htm
When someone clicks on a link within an iframe (child page), how do I get the parent page to scroll to the top? The issue is the child page will remain in the same spot of the page, because the iframe has a lot of height larger than the parent page.
Please note: the parent and child pages are on different sub domains.
I created a demo to show this:
http://www.apus.edu/_test/iframe/index.htm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
诀窍是将以下
onload="window.parent.parent.scrollTo(0,0)"
附加到iframe
即可!The trick is to append the following
onload="window.parent.parent.scrollTo(0,0)"
to theiframe
and that should do it!如果您有跨源(iframe 和父级具有不同的域),则仅调用 window.scrollTo(0,0) 将不起作用。
跨域的一种解决方案是从 iframe 向父级发送可信消息。
在 iframe 中编码:
然后在父级中编码:
If you have cross origins (the iframe and the parent have different domains), then just calling window.scrollTo(0,0) won't work.
One solution to cross-origin is to send a trusted message from the iframe to the parent.
Code inside the iframe:
Then code in the parent:
在 iframe 中使用 JavaScript,引用父级并调用 scroll( ) 方法。
(注意。如果 iframe Url 与父级的域不同,则此操作将不起作用。)
Using JavaScript within the iframe, reference the parent and call the scroll() method.
(Note. This will not work if the iframe Url is a different domain than the parent.)
在 Iframe 页面内。
在父页面上:
Within the Iframe page.
On The parrent page:
带动画
With animation