1. Get the target element
const element = document. getElementById ( 'myElement' )
2. Get the height of the target element
const elementHeight = element. clientHeight
3. Obtain the vertical displacement of the upper left corner of the target element relative to Element.offsetParent
the node (in this article, it is the distance from the top, which does not change with page scrolling)
const elementOffsetTop = element. offsetTop
4. Get the height of the browser window
const windowHeight = document. documentElement. clientHeight
5. Obtain the vertical scrolling distance of the page (changes with the page scrolling)
const windowScrollTop = document. documentElement. scrollTop
6. Determine whether the element is within the visible area
if ( ( windowScrollTop <= elementOffsetTop + elementHeight) && ( windowScrollTop >= elementOffsetTop - windowHeight) ) {
console. log ( '元素在可视区域出现' )
} else {
console. log ( '元素咋可视区域消失' )
}
7. Complete demo code
<! 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>