【转】简单的判断滚动到底部加载更多

2,636 阅读1分钟

原文地址:www.jianshu.com/p/7dd126a7d…

方法是直接使用下面代码即可,至于滚动到离底部多少距离,请自行调整

js:

    window.onscroll= function(){
        //文档内容实际高度(包括超出视窗的溢出部分)
        var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
        //滚动条滚动距离
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        //窗口可视范围高度
        var clientHeight = window.innerHeight || Math.min(document.documentElement.clientHeight,document.body.clientHeight);
        
        if(clientHeight + scrollTop >= scrollHeight){
            console.log("===加载更多内容……===");
        }
    }

jquery:

<script>
    $(window).on("resize scroll",function(){
             
        var windowHeight = $(window).height();//当前窗口的高度             
        var scrollTop = $(window).scrollTop();//当前滚动条从上往下滚动的距离            
        var docHeight = $(document).height(); //当前文档的高度 
        console.log(scrollTop, windowHeight, docHeight);
        //当 滚动条距底部的距离 + 滚动条滚动的距离 >= 文档的高度 - 窗口的高度  
        //换句话说:(滚动条滚动的距离 + 窗口的高度 = 文档的高度)  这个是基本的公式  
        if (scrollTop + windowHeight >= docHeight) { 
            console.log("===加载更多数据===");
        }
    });
</script>