vue 用纯js监听滚动条到底部 实现上拉加载

在移动端网页项目中,基本都会有列表页的上拉加载功能。在这篇文章中,我结合vue的生命周期用纯js写了一个监听滚动条的函数。

怎样用纯js判断滚动条是否到底部

先了解几个重点要素:

  1. 获取滚动条到顶部的位置:document.documentElement.scrollTopdocument.body.scrollTop
  2. 获取当前窗口内容可视区:document.documentElement.clientHeightdocument.body.clientHeight
  3. 获取滚动条的总高度:document.documentElement.scrollHeightdocument.body.scrollHeight
  4. 触发监听的函数:window.onscroll = function(){...}
  5. 判断到底部的等式:滚动条到顶部的位置 + 当前窗口内容可视区 == 滚动条的总高度
主要代码
  1. 监听的函数
created() {
  let that = this;
  window.onscroll = function(){
    // scrollTop 滚动条滚动时,距离顶部的距离
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    // windowHeight 可视区的高度
    var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
    // scrollHeight 滚动条的总高度
    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    // 滚动条到底部的条件
    if(scrollTop + windowHeight == scrollHeight){
      // 加载数据
      that.loadMore();
    }
  }
},
  1. data
data () {
  return {
    dataList: [], // 数据数组
    page: 1, // 第几页
    upLoading: true, // 是否加载数据
  }
},
  1. 加载数据(以下的getListApi是我自己封装的函数)
loadMore() {
  this.page++;
  if(this.upLoading) {
    getListApi({
      page: this.page,
      pagesize: 10
    }).then(res=>{
      if(res.data.length > 0) {
        this.upLoading = true;
        let dataList = this.dataList;
        for (let i = 0; i < res.data.length; i++) {
          dataList.push(res.data[i])
        }
        this.dataList = dataList;
      }else {
        this.upLoading = false;
      }
    })
  }
},

猜你喜欢

转载自blog.csdn.net/mossbaoo/article/details/88555851