如何获取 iframe 的 scrollTop [英] How to get scrollTop of an iframe

查看:31
本文介绍了如何获取 iframe 的 scrollTop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 window 是 iframe 时,jQuery 的 scrollTop 返回 null.有没有人能够弄清楚如何获得 iframe 的 scrollTop?

jQuery's scrollTop returns null when window is an iframe. Has anyone been able to figure out how to get scrollTop of an iframe?

更多信息:

我的脚本在 iframe 本身中运行,父窗口在另一个域上,所以我无法访问 iframe 的 ID 或类似的东西

my script is running in the iframe itself, the parent window is on another domain, so I can't access the ID of the iframe or anything like that

推荐答案

您可以使用此设置来设置 scrollTop:

You can set scrollTop by using this setup:

$("html,body").scrollTop(25);

所以你可以试试这样:

$("html,body").scrollTop();

因为不同的浏览器在不同的元素(body 或 html)上设置了 scrollTop.

Because different browsers set the scrollTop on different elements (body or html).

来自 scrollTo 插件:

但这在某些浏览器中可能仍然会失败.以下是 Ariel Flesher 的 jQuery 的 scrollTo 插件 源代码中的相关部分:

But that will probably still fail in certain browsers. Here is the relevant section from the source code of Ariel Flesher's scrollTo plugin for jQuery:

// Hack, hack, hack :)
// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
$.fn._scrollable = function(){
  return this.map(function(){
    var elem = this,
      isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

    if( ! isWin ) {
      return elem;
    }


    var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;

     return $.browser.safari || doc.compatMode == 'BackCompat' ?
       doc.body : 
       doc.documentElement;
  });
};

然后您可以运行:

$(window)._scrollable().scrollTop();

确定 iframe 向下滚动了多远.

To determine how far the iframe has scrolled down.

这篇关于如何获取 iframe 的 scrollTop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆