在移动端网页项目中,基本都会有列表页的上拉加载功能。在这篇文章中,我结合vue的生命周期用纯js写了一个监听滚动条的函数。
怎样用纯js判断滚动条是否到底部
先了解几个重点要素:
- 获取滚动条到顶部的位置:
document.documentElement.scrollTop
、document.body.scrollTop
- 获取当前窗口内容可视区:
document.documentElement.clientHeight
、document.body.clientHeight
- 获取滚动条的总高度:
document.documentElement.scrollHeight
、document.body.scrollHeight
- 触发监听的函数:
window.onscroll = function(){...}
- 判断到底部的等式:滚动条到顶部的位置 + 当前窗口内容可视区 == 滚动条的总高度
主要代码
- 监听的函数
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();
}
}
},
- data
data () {
return {
dataList: [], // 数据数组
page: 1, // 第几页
upLoading: true, // 是否加载数据
}
},
- 加载数据(以下的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;
}
})
}
},