<div style="background-color: blue;width:100vw;height:5000px"></div>
<div id="img" style="background-color: blueviolet;width:100vw;height:500px"></div>
clientHeight
scrollTop
offsetTop
判断document.addEventListener('scroll', () => {
// 屏幕可视区域的高度
const clientHeight = document.documentElement.clientHeight
// 滚动条滚动的距离
const scrollTop = document.documentElement.scrollTop
// 图片元素距离顶部的距离
const offsetTop = document.getElementById('img').offsetTop
if (clientHeight + scrollTop > offsetTop) {
// 已进入可视区域
// do something
}
})
getBoundingClientRect
document.addEventListener('scroll', () => {
const domRect = document.getElementById('img').getBoundingClientRect()
const innerHeight = window.innerHeight
if (domRect.top <= innerHeight) {
// 已进入可视区域
// do something
}
})