JavaScript判断是否滚动到底部–可用于列表的滚动加载1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57//滚动条在Y轴上的滚动距离
function getScrollTop() {
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if (document.body) {
bodyScrollTop = document.body.scrollTop;
}
if (document.documentElement) {
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//文档的总高度
function getScrollHeight() {
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if (document.body) {
bodyScrollHeight = document.body.scrollHeight;
}
if (document.documentElement) {
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
//浏览器视口的高度
function getWindowHeight() {
var windowHeight = 0;
if (document.compatMode == "CSS1Compat") {
windowHeight = document.documentElement.clientHeight;
} else {
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
//判断是否滚动到底部
function isBottom(distance) {
let bottomDistance = distance || 0;
if (getScrollTop() + getWindowHeight() + bottomDistance >= getScrollHeight()) {
//console.log("已经到底部");
return true;
} else {
return false;
}
};
export { isBottom }
//引用 import {isBottom} from './isBottom.js'
//滚动加载使用
//vue中生命周期mounted执行
window.addEventListener('scroll', this.loadMore) //this.loadMore为滚动加载的方法
//移除监听
//vue中生命周期beforeDestroy执行
window.removeEventListener('scroll', this.loadMore)
欢迎前端小伙伴加群一起学习进步:163958730