【问题标题】:Scroll to top of parent from iframe on different domains从不同域的 iframe 滚动到父级顶部
【发布时间】:2017-08-13 01:05:55
【问题描述】:

我在页面中嵌入了一个 iframe。它们都在不同的域上,但我可以访问两者。

当点击 iframe 中的链接时,我想滚动到父窗口的顶部。是这样的:

在 iframe 页面内。

window.parent.ScrollToTop(); // Scroll to top function

在父页面上:

window.ScrollToTop = function(){
  $('html,body', window.document).animate({
    scrollTop: '0px'
    }, 'fast');
  };

这可能吗?

【问题讨论】:

  • 同源策略阻止你访问windows跨域调用任何此类方法。这样做的方法是使用postMessage 让 iframe 向父级发送消息,然后父级可以自行滚动。

标签: javascript jquery html iframe cross-domain


【解决方案1】:

如果您有权访问父域,那么您可以使用:

window.top.scroll(0,0)

或者如果你想要一些动画使用:

$(window.top.document).find("body").animate({
scrollTop: 0
}, 600);

【讨论】:

  • 我可以访问两者,但它们位于不同的域中。因此,当我尝试调用 window.parent 时,它会给出关于跨域的错误。
  • 是的,它会显示,因为 Javascript 不允许通过其他域更改一个域的任何行为。欲了解更多信息,请查看:stackoverflow.com/questions/4724904/…
猜你喜欢
  • 2011-04-17
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 2011-04-27
相关资源
最近更新 更多