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. 完全なデモ コード
<!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>