1、获取目标元素
const element = document.getElementById('myElement')
2、获取目标元素的高度
const elementHeight = element.clientHeight
3、获取目标元素左上角相对于 Element.offsetParent 节点的垂直位移(本文中即为距离顶部的距离,不随页面滚动变化)
const elementOffsetTop = element.offsetTop
4、获取浏览器窗口的高度
const windowHeight = document.documentElement.clientHeight
5、获取页面垂直的滚动距离(随页面滚动变化)
const windowScrollTop = document.documentElement.scrollTop
6、判断元素是否在可见区域内
if ((windowScrollTop <= elementOffsetTop + elementHeight) && (windowScrollTop >= elementOffsetTop - windowHeight)) {
console.log('元素在可视区域出现')
} else {
console.log('元素咋可视区域消失')
}
7、完整 Demo 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.content-block {
margin-bottom: 20px;
width: 100%;
height: 350px;
background-color: lightblue;
}
</style>
</head>
<body>
<section>
<div class="content-block"></div>
<div class="content-block"></div>
<div id="myElement" class="content-block" style="background-color: lightcoral;"></div>
<div class="content-block"></div>
<div class="content-block"></div>
</section>
<script>
setInterval(() => {
const element = document.getElementById('myElement')
const elementHeight = element.clientHeight
const elementOffsetTop = element.offsetTop
const windowHeight = document.documentElement.clientHeight
const windowScrollTop = document.documentElement.scrollTop
if ((windowScrollTop <= elementOffsetTop + elementHeight) && (windowScrollTop >= elementOffsetTop - windowHeight)) {
console.log('元素在可视区域出现')
} else {
console.log('元素咋可视区域消失')
}
}, 2000)
</script>
</body>
</html>
|