JavaScript 判断目标元素是否在可视区域内

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、判断元素是否在可见区域内
// windowScrollTop = elementOffsetTop - windowHeight (目标元素刚进入可视区域)
// windowScrollTop = elementOffsetTop + elementHeight(目标元素刚离开可视区域)
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>

猜你喜欢

转载自blog.csdn.net/qq_41548644/article/details/120980410
今日推荐