html结构:
<div id="container"> // 视觉容器
<div id="wrap"> // 实际滚动的元素
// 无限列表,倒数第3个出现时加载下一页
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p8</p>
<p>p</p>
<p>p</p>
</div>
</div>
实现:
主要api是getBoundingClientRect()
实现思路:target(倒数第3个节点)距离视口顶部的距离 <= container距离视口顶部的距离 - container的高度 时加载下一页
如图,4就是target距离container底部的距离,当4的值小于0时,就可以触发一次加载(不涉及加载逻辑,比如判断请求是否返回等)
js代码:
document.getElementById('container').addEventListener('scroll', function() {
const wrap = document.getElementById('wrap')
const ChildLength = wrap.children.length
const target = wrap.children[ChildLength - 3] // 倒数第3个子元素露出时再次加载
// target距离视口顶部的距离 = container距离视口顶部的距离 - container的高度
targetToTop = target.getBoundingClientRect().top
containerToTop = document.getElementById('container').getBoundingClientRect().top
containerHeight = document.getElementById('container').getBoundingClientRect().height
if (targetToTop <= containerToTop + containerHeight) {
console.log('露出');
}
})