JavaScript page scrolling distance

Different web browsers get different rolling distance method

There are two modes in the browser when rendering the page: "Standard mode (CSS1Compat)", "promiscuous mode / quirks mode (BackCompat)"
By default, all in standard mode rendering,
if the page is not written document declaration will According to "promiscuous mode / quirks mode" to render

  • Document declaration:<!DOCTYPE html>
1.IE9 well above IE9 browser
window.pageXOffset;//水平方向
window.pageYOffset;//垂直方向
2. Under standard mode browser
document.documentElement.scrollTop;//垂直方向
document.documentElement.scrollLeft;//水平方向
3. mixed under (weird) mode browser
document.body.scrollTop;//垂直方向
document.body.scrollLeft;//水平方向
4. resolve compatibility issues page scrolling distance: the distance from package into the page scrolling method
<script>
    window.onscroll = function () {//鼠标的滚动事件
        let{x, y} = getPageScroll();//对象的解构赋值——ES6新增
        console.log(x, y);//答应水平与垂直方向的滚动距离
        
        function getPageScroll() {//获取网页滚动距离的方法
            let x, y;
            if (window.pageXOffset){//查看有无pageXOffset属性:IE9以及IE9以上的浏览器
                x = window.pageXOffset;
                y = window.pageYOffset;
            }else if (document.compatMode ==  "BackCompat"){//混杂(怪异)模式下浏览器
                x = document.body.scrollLeft;
                y = document.body.scrollTop;
            }else {//标准模式下浏览器
                x = document.documentElement.scrollLeft;
                y = document.documentElement.scrollTop;
            }
            return {//返回水平距离、垂直距离
                x:x,
                y: y
            }
        }
    }

</script>

Guess you like

Origin blog.csdn.net/Cao_Mary/article/details/90232473