实现思路

  • 通过判断当前页面是否到达底部来设置按钮的点击事件。
  • 要判断当前页面是否到达底部需要用到三个距离——距离顶部的距离scrollTop、可视区域的高度clientHeight、滚动条的高度scrollHeight。

代码(在vue项目中使用)

mounted() {
this.$nextTick(() => {
// 进入nexTick
const body: any = document.getElementById("app"); // 获取滚动条的dom
// 获取距离顶部的距离
const scrollTop = body.scrollTop;
// 获取可视区的高度
const windowHeight = body.clientHeight;
// 获取滚动条的总高度
const scrollHeight = body.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight) {
// 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
this.show = true
} else {
this.show = false;
// 滚动事件
body.onscroll = () => {
console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
if (scrollTop + windowHeight >= scrollHeight) {
// 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
this.show = true
}
}
}
console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
});
}