getBoundingClientRect(),获取元素的宽度、高度、距离可视区域顶部距离等
1.先判断目标元素头部进入可视区域。getBoundingClientRect()方法里面有一个top,可以获取目标元素顶部距离可视区域顶部的距离,目标元素top <= 可视区域高度时,就代表目标元素进入。
2.再判断目标元素离开可视区域。getBoundingClientRect()方法里面有一个bottom,可以获取目标元素底部距离可视区域顶部的距离,目标元素bottom <= 0时,就代表目标元素还在可视区域内。
document.querySelector("#box").addEventListener("scroll", (e) => {
// 获取容器高度
const boxHeight = e.target.getBoundingClientRect().height;
// 需要判断的目标元素
const view = document.querySelector("#dot").getBoundingClientRect();
if (view.top <= boxHeight && view.bottom >= 0) {
console.log("目标进入");
} else {
console.log("目标出去");
}
});
附带style和html
<style>
html,
body,
div {
padding: 0;
margin: 0;
}
#box div {
height: 500px;
}
#dot {
background: coral;
}
</style>
<div id="box" style="height: 100vh; overflow-y: auto">
<div></div>
<div></div>
<div></div>
<div id="dot"></div>
<div></div>
<div></div>
</div>