1.数据懒加载
数据懒加载通过监听滚动事件实现,判断滚动条的高度对比滚动条到顶部的距离和滚动元素的高度。
<body>
<div class="container">
</div>
<script>
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
let domArr = []
const container = document.querySelector('.container')
//原理:滚动条到顶部的最大距离 + 可视高度 = 滚动条高度
//当快要到达滚动条底部的时候(如:滚动条到顶部距离+可视高度 > 滚动条高度-20px)触发扩容函数,就实现了数据懒加载
container.addEventListener('scroll', (e) => {
// console.log('滚动条到顶部的距离:', e.srcElement.scrollTop);
// console.log('可视高度:', e.srcElement.offsetHeight);
// console.log('滚动条的高度:', e.srcElement.scrollHeight);
let top = e.srcElement.scrollTop
let viewHeight = e.srcElement.offsetHeight
let height = e.srcElement.scrollHeight
if (top + viewHeight > height - 20) {
if (end <= arr.length - 1) {
domFn()
}
}
})
let end = 0
function domFn() {
domArr.push(...arr[end])
end++
let str = ''
domArr.forEach(item => {
str = str + `<p>${item}</p>`
})
container.innerHTML = str
}
domFn()
</script>
<style>
* {
padding: 0;
margin: 0;
}
.container {
height: 200px;
width: 100%;
overflow: auto;
border: 1px solid black;
}
p {
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid red;
box-sizing: border-box;
}
</style>
</body>