首先dom元素有个方法Element.getBoundingClientRect()
这个方法没有参数,用于获得Element到浏览器窗口文档显示区的上边和左边的的距离以及元素自身的宽高。(是可视范围的距离,不包括卷起的部分)
如top:element上边到浏览器宽口文档显示区顶部的距离。
bottom:element下边到浏览器宽口文档显示区顶部的距离。
left:element左边到浏览器窗口文档显示区左边的距离。
right:element右边到浏览器窗口文档显示区右边的距离。
width:element自身的宽。
height:element自身的高。
window.innerHeight 是返回浏览器窗口文档显示区的高度(不包括菜单栏工具栏那些)
知道了这两个知识点,判断元素是不是在浏览器窗口的有效区域还不简单吗,Element.getBoundingClientRect().bottom是必须要大于0的,Element.getBoundingClientRect().top是不能大于浏览器窗口文档显示区域的高的也就是window.innerHeight
完整代码如下:
window.addEventListener("scroll",()=>{
const bottom = dataSectionEl.getBoundingClientRect.bottom
const top = dataSectionEl.getBoundingClientRect.top
if(bottom >= 0 && top<= window.innerHeight){
//内容
}
})