JS关于scrollTop和可视区域clientWidth

一、scrollTop,scrollLeft

要获得页面的scrollTop及scrollLeft,在不同的浏览器中是不一样的:

谷歌浏览器和没声明DTD的文档,通过document.body.scrollTop;来获得

火狐和其他浏览器,通过document.documentElement.scrollTop;来获得

ie9+和最新的浏览器 均可以通过window.pageYOffset;来获得

综上,可以封装如下访问方法:

<script>
    function scrollJson() {
        if(window.pageYOffset != null) {//ie9+及其他浏览器
            return {
                left: window.pageXOffset,
                top: window.pageYOffset
            }
        }
        else if (document.compatMode == "CSS1Compat"){//声明了DTD
            return {
                left: document.documentElement.scrollLeft,
                top: document.documentElement.scrollTop
            }
        }
        return {
            left: document.body.scrollLeft,
            top: document.body.scrollTop
        }
    }

    window.onscroll = function () {
        console.log(scrollJson());
    }
</script>

 

二、同理,可以获得可视区域

function clientSize(){
        if(window.innerWidth != null) {
            return {
                width: window.innerWidth,
                height: window.innerHeight
            }
        }
        else if(document.compatMode == "CSS1Compat") {
            return {
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight
            }
        }
        return {
            width: document.body.clientWidth,
            height: document.body.clientHeight
        }
    }

 

posted @ 2017-01-16 16:19  Dadada胖纸er  阅读(252)  评论(0编辑  收藏  举报