三种方式实现滚动到底部加载更多

14,055 阅读1分钟

原生js实现思路

需要三个高度:scrollHeight(文档内容实际高度,包括超出视窗的溢出部分)、scrollTop(滚动条滚动距离)、clientHeight(窗口可视范围高度)。当 clientHeight + scrollTop >= scrollHeight 时,表示已经抵达内容的底部了,可以加载更多内容。

// 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("===加载更多内容……===");
    }
}

Vue的实现方式

mounted() {
  // 监听滚动
  window.addEventListener('scroll',this.handleScroll,true)
},

// 滚动操作
handleScroll(e){
  let dom = document.querySelector('.main_content')
  //文档内容实际高度(包括超出视窗的溢出部分)
  let scrollHeight = Math.max(dom.scrollHeight, dom.scrollHeight);
  //滚动条滚动距离
  let scrollTop = e.target.scrollTop;
  //窗口可视范围高度
  let clientHeight = dom.innerHeight || Math.min(dom.clientHeight,dom.clientHeight);
  if(clientHeight + scrollTop >= scrollHeight){
    if(this.pageSize > this.total ) return;
    this.pageSize += 10
    this._getArchives()
  }
},

// 销毁监听  (坑:移除监听事件时加true否则销毁不成功)
beforeDestroy(){
  window.removeEventListener("scroll",this.handleScroll,true)
}

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>