原生js判断滚动条滚到底部
日期: 2020-06-18 分类: 个人收藏 397次阅读
如题
开发中经常遇到,滚动条滚到底部加载下一页,或者给出提示的需求,也踩过一些坑。
坑的表现:
1)还没到底部,就已经触发了加载下一页的方法(以前遇到过,但是错误的代码已经忘了)
2)多次触发,导致多次调用或者一些异常情况
3)在滚动的时候,偶尔会出现ScrollTop值为空或者undefined的情况
网上的方法不一定奏效的,贴两个原生解决方法:
//滚动条在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;
}
export var scrollBottom = function () {
if (getScrollTop() + getWindowHeight() == getScrollHeight()) {
return true;
} else {
return false;
}
// let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
// let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// if (scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
// return true;
// } else {
// return false;
// }
};
写在公共util方法里,调用即可。
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
精华推荐