1、css
#box{
width: 500px;
height: 500px;
overflow-y:auto;
}
2、html
<div id="box">
<!--列表内容放在这里-->
<!--列表内容如果一次加载不完,一定要保证初次加载时的列表总高度超过box的高度,否则不会产生滚动条-->
</div>
3、js
function addData() {
let box = document.getElementById('box');
// 这里用循环生成代替ajax加载数据
for (let i = 0; i < 50; i++) {
let span = document.createElement('span');
span.innerHTML = 'test' + i + '<br>';
box.appendChild(span);
}
}
addData();
window.onscroll = function () {
//scrollTop就是触发滚轮事件时滚轮的高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
console.log("滚动距离" + scrollTop);
//变量windowHeight是可视区的高度
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
console.log("可视高度" + windowHeight);
//变量scrollHeight是滚动条的总高度
var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
console.log("总高度" + scrollHeight);
//判断滚动条是否到底部
if (scrollTop + windowHeight == scrollHeight) {
//加载数据
console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
addData();
}
}
