1. 原生JS(适用于PC端,iphone上有bug-- 推荐使用第二种)
//用于计算-当前窗口的高度
function getClientHeight() {
if(document.body.clientHeight&&document.documentElement.clientHeight)
{
return (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
} else {
return (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
}
}
//监听滚动底部事件
function winScroll (){
let scrollTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; //滚动条距离顶部的高度
let scrollHeight = getClientHeight(); //当前页面的总高度
let clientHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); //当前可视的页面高度
// console.log("top:"+scrollTop+",doc:"+scrollHeight+",client:"+clientHeight);
if(Math.ceil(scrollTop + scrollHeight) >= clientHeight){ //距离顶部+当前高度 >=文档总高度 即代表滑动到底部
//调用分页功能等 滑动底部事件
console.log('到底了');
}
}
//给window添加监听
window.addEventListener('scroll', winScroll);//必要时移除监听 window.removeEventListener('scroll', winScroll, false)
2. 第三方库,兼容移动端(推荐)
使用详情见read.md