网页实现滚动分页加载
瀑布流滚动加载,用于展示长列表,当列表即将滚动到底部时,会触发事件并加载更多列表项。
技术准备
核心属性:
scrollTop: 网页被卷去内容得高度
clientHeight: 当前可视区域的高度
scrollHeight: 文档流高度
distance:页面到达底部多远距离触发
判断是否到达底部公式:
scrollTop+clientHeight>=scrollHeight-distance
具体判断方法
/**
\* 添加滚动事件
*/
addScroll(): void {
window.addEventListener("scroll", this.watchScroll, true);
}
/**
\* 移除滚动事件
*/
removeScroll(): void {
window.removeEventListener("scroll", this.watchScroll, true);
}
// 滚动分页,屏幕滚动事件回调
watchScroll(): void {
// 滚动条到底部且没有完成搜索(还有更多数据)
if (this.isWindowBottom() && !this.pageFinished) {
++this.currentPage;
this.recieveRecommend();
}
}
// 滚动分页,判断当前滚动条是否已到达底部
public isWindowBottom(): boolean {
// 滚动条滚动时,距离顶部的距离
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
// 可视区的高度,数值上与“滚动条滚轮的高度”相等,只是长度单位不同
const windowHeight =
document.documentElement.clientHeight || document.body.clientHeight;
// 滚动条的总高度
const scrollHeight =
document.documentElement.scrollHeight - 100 ||
document.body.scrollHeight - 100;
return scrollTop + windowHeight >= scrollHeight;
}