js 滚动到底部的时候触发的事件
scrollTop为滚动条在Y轴上的滚动距离。
clientHeight为内容可视区域的高度。
scrollHeight为内容可视区域的高度加上溢出(滚动)的距离(当前可滚动的页面的总高度)
这个三个属性的介绍就可以看出来,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if(scrollHeight-scrollTop-windowHeight <=300){
}else{
}
});
window.addEventListener('scroll', scroll)
function scroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
if (scrollTop === 0) {
console.log('滚动到顶了');
}
if (scrollTop + clientHeight >= scrollHeight) {
console.log('滚动到底了');
}
}
window.removeEventListener('scroll', scroll) // 移除滚动事件
在部分浏览器上,到底部时,触发不了
可以考虑:
1.用offsetHeight代替clientHeight ,多计算边框的距离
2.scrollTop的实时监听值可能是小数,采用Math.ceil(scrollTop),向上取整,避免少那个零点几的距离