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>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值