How to get scrollTop of an iframe

后端 未结 10 1712
一生所求
一生所求 2020-12-03 03:33

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

more info:

my script is runn

10条回答
  •  隐瞒了意图╮
    2020-12-03 03:59

    You can set scrollTop by using this setup:

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

    So you could try getting it like this:

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

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

    From the scrollTo plugin:

    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;
      });
    };
    

    You may then run:

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

    To determine how far the iframe has scrolled down.

提交回复
热议问题