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

前端 未结 11 1742
孤街浪徒
孤街浪徒 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:18

    I know its been quite a while since this thread was updated, but this is a function I created that allows developers to find the root element that actually hosts has a working "scrollTop" property. Tested on Chrome 42 and Firefox 37 for Mac OS X (10.9.5):

    function getScrollRoot(){
        var html = document.documentElement, body = document.body,
            cacheTop = ((typeof window.pageYOffset !== "undefined") ? window.pageYOffset : null) || body.scrollTop || html.scrollTop, // cache the window's current scroll position
            root;
    
        html.scrollTop = body.scrollTop = cacheTop + (cacheTop > 0) ? -1 : 1;
        // find root by checking which scrollTop has a value larger than the cache.
        root = (html.scrollTop !== cacheTop) ? html : body;
    
        root.scrollTop = cacheTop; // restore the window's scroll position to cached value
    
        return root; // return the scrolling root element
    }
    
    // USAGE: when page is ready: create a global variable that calls this function.
    
    var scrollRoot = getScrollRoot();
    
    scrollRoot.scrollTop = 10; // set the scroll position to 10 pixels from the top
    scrollRoot.scrollTop = 0; // set the scroll position to the top of the window
    

    I hope you find this useful! Cheers.

提交回复
热议问题