Cross-browser method for detecting the scrollTop of the browser window

前端 未结 11 1755
孤街浪徒
孤街浪徒 2020-11-27 12:38

What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and

11条回答
  •  盖世英雄少女心
    2020-11-27 13:14

    YUI 2.8.1 code does this:

    function getDocumentScrollTop(doc) 
    {
       doc = doc || document;
    
       //doc.body.scrollTop is IE quirkmode only
       return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
    }
    

    I think jQuery 1.4.2 code (a bit translated for humans) and supposing I understood it properly does this:

    function getDocumentScrollTop(doc) 
    {
       doc = doc || document;
       win = doc.defaultView || doc.parentWindow; //parentWindow is for IE < 9
    
       result = 0;
       if("pageYOffset" in win) //I'don't know why they use this, probably they tested it to be faster than doing: if(typeof win.pageYOffset !== 'undefined')
          result = win.pageYOffset;
       else
          result = (jQuery.support.boxModel && document.documentElement.scrollTop) || 
                   document.body.scrollTop;
    
       return result;
    }
    

    Unfortunatley extracting the value of jQuery.support.boxModel is almost impossible because you would have to add a temporary child element into document and do the same tests jQuery does.

提交回复
热议问题