document.documentElement.scrollTop return value differs in Chrome

后端 未结 5 1283
既然无缘
既然无缘 2020-12-03 02:52

I am trying to process some code based on the \'document.documentElement.scrollTop\' value. It returns \'348\' in FF and IE but in Chrome it return

5条回答
  •  感情败类
    2020-12-03 03:24

    Use window.scrollY where possible, it's designed to be consistent across browsers. If you need to support IE, then I'd recommend the following to only use window.scrollY if it's available:

    typeof window.scrollY === "undefined" ? window.pageYOffset : window.scrollY
    

    window.scrollY will be evaluated as false if it returns 0, so doing window.scrollY || window.pageYOffset would technically check window.pageYOffset whenever window.scrollY were 0, which obviously isn't ideal if window.pageYOffset did not also equal 0.

    Also note that if you need to get the scroll value frequently (every frame/every scroll) as is often the case, you might want to check if window.scrollY is defined beforehand. I like to use this small helper function I wrote to do exactly that, along with using requestAnimationFrame - it should work in IE10 and up.

    function registerScrollHandler (callback) {
        "use strict"
    
        var useLegacyScroll = typeof window.scrollY === "undefined",
            lastX = useLegacyScroll ? window.pageXOffset : window.scrollX,
            lastY = useLegacyScroll ? window.pageYOffset : window.scrollY
    
        function scrollHandler () {
            // get the values using legacy scroll if we need to
            var thisX = useLegacyScroll ? window.pageXOffset : window.scrollX,
                thisY = useLegacyScroll ? window.pageYOffset : window.scrollY
    
            // if either the X or Y scroll position changed
            if (thisX !== lastX || thisY !== lastY) {
                callback(thisX, thisY)
    
                // save the new position
                lastX = thisX
                lastY = thisY
            }
    
            // check again on the next frame
            window.requestAnimationFrame(scrollHandler)
        }
    
        scrollHandler()
    }
    

    Use the function like this:

    registerScrollHandler(function (x, y) {
        /* your code here :) */
        console.log("Scrolled the page", x, y)
    })
    

提交回复
热议问题