需求
- 要求用戶閱讀完本頁所有內容后,下一步按鈕才可以點擊。
實現思路
- 通過判斷當前頁面是否到達底部來設置按鈕的點擊事件。
- 要判斷當前頁面是否到達底部需要用到三個距離——距離頂部的距離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);
});
}