js 判断滚动条 是否滚动到底部

解决问题思路

滚动条距离上面的滚动高度(scrollTop) + 滚动条本身高度 = 整个页面的高度(pageHeight)

关键点:滚动条本身高度是多少

事实上,这里就有一个思想误区,人会想直接获取滚动条高度(但找不到这个API,同时滚动条表现出来的高度,也会虽内容变长变短)。

其实你只要考虑一下,为什么会出现滚动条。出现滚动条代表超出可视窗口,它的滚动距离就是超出部分,而可视窗口高度就是滚动条对应的真实高度

 //滚动条距离顶部高度
        function getScrollTop() {
            var scrollTop=0;
            if(document.documentElement&&document.documentElement.scrollTop) {
                scrollTop=document.documentElement.scrollTop;
            }
            else if(document.body)  {
                scrollTop= document.body.scrollTop;
            }
            return  Math.ceil(scrollTop);
        }

        //滚动条本身高度:就是可视窗口高度
        function getScrollBarHeight(){
            let scrollBarHeight = document.documentElement.clientHeight;
            return Math.ceil(scrollBarHeight);
        }
        
        //整个页面高度
        function getPageHeight()  {
            return Math.ceil(Math.max(document.body.clientHeight,document.documentElement.scrollHeight));
        }


        window.onscroll = function () {
            let top = getScrollTop();
            let ch = getScrollBarHeight();
            let sh = getPageHeight();
            if (top + ch >= sh) {
                console.log("到达底部");
            }else{
               console.log("没有到达底部");
            }
        }

 

posted @ 2021-09-03 11:32  tengyuxin  阅读(1364)  评论(0编辑  收藏  举报