如何判断元素是否在可视区域内呢?然后搞一些事情

16,937 阅读3分钟

在学习判断元素是否在可视区域时,我们首先的了解一些元素的位置值和大小值。

元素的位置信息和大小

大部分属性都是对应的,所以下面都只写一个。

  • clientWidth:元素内容区宽度加上左右内边距宽度,即clientWidth = content + padding

  • offsetTop,元素的上外边框至包含元素的上内边框之间的像素距离。 // 元素的偏移量不会随着滚动条的滚动而发生改变。并且是相对于定位父元素的位置计算的。如果没有定位的父元素就获取的是到窗口的距离,从元素的外边框计算到父元素的内边框

  • document.documentElement.scrollHeight: 获取浏览器窗口的总高度 。包括滚动条的隐藏高度。,如果没有滚动条,则他就等于document.documentElement.clientWidth

  • document.documentElement.clientWidth:获取视口宽度。就是浏览器窗口的宽度。

  • getBoundingClientRect()返回元素的大小及其相对于视口的位置。 这里获取的大小包括边框,内容和内边距。 获取相对于视口的位置时,都是视口到外边框的距离。

  • document.documentElement.scrollTop:获取滚动条滚动的高度。这个值是可以设置的。

了解了上面的一些属性,我们就可以学习第一种判断方法了

通过元素的位置信息和滚动条滚动的高度来判断了

function isContain(dom) {
    // 获取可视窗口的盖度。
    const screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    // 获取滚动条滚动的高度
    const scrollTop = document.documentElement.scrollTop;
    // 获取元素偏移的高度。就是距离可视窗口的偏移量。
    const offsetTop = dom.offsetTop;
    return offsetTop - scrollTop <= screenHeight;
}

通过getBoundingClientRect方法来获取元素的位置信息,然后加以判断(这种方法是我之前没有见过的)

首先来介绍一下getBoundingClientRect方法。

他是dom对象的一个方法。返回一个DOMRect对象。该对象拥有left, top, right, bottom, x, y, width, 和 height属性。

当页面发生滚动的时候,top, left, right, bottom属性值都会随之改变。

top:就是元素上外边框到视口顶端距离。

left:就是元素左外边框到视口左端距离。

bottom:就是元素下外边框到视口顶端距离。

right:就是元素右外边框到视口左端距离。 如果想要判断子元素是否在可视区域内,只需要:

  • top 大于等于 0
  • left 大于等于 0
  • bottom 小于等于视窗高度
  • right 小于等于视窗宽度
    function isContain(dom) {
      const totalHeight = window.innerHeight || document.documentElement.clientHeight;
      const totalWidth = window.innerWidth || document.documentElement.clientWidth;
      // 当滚动条滚动时,top, left, bottom, right时刻会发生改变。
      const { top, right, bottom, left } = dom.getBoundingClientRect();
      return (top >= 0 && left >= 0 && right <= totalWidth && bottom <= totalHeight);
    }

通过webAPI,Intersection Observer来实现监听。

详细讲解,可以参考mdn:developer.mozilla.org/zh-CN/docs/… Intersection Observer API 会注册一个回调函数,每当被监视的元素进入或者退出另外一个元素时(或者 viewport),或者两个元素的相交部分大小发生变化时,该回调方法会被触发执行。

const options = {
    root: // 用于检查目标的可见性。必须是目标元素的祖先节点。
    rootMargin: "上右下左" // 给祖先节点设置margin,等同于css中的margin。用来扩展或缩小`rootBounds`这个矩形的大小,从而影响`intersectionRect`交叉区域的大小。
    threshold: //表示当子元素和父元素覆盖多少时触发回调函数。
}

const observer = new IntersectionObserver((entries) => {
    // 当满足条件是搞一些事情
    // 这里通过判断entries[0].isIntersecting来判断是否在可视区域
}, options)

observer.observe(dom);

下面就是三种方法判断的例子了

该例子就是如果子元素没有显示在当前可是窗口中时,窗口的背景颜色显示为绿色,反之显示为蓝色。

  <style>
    .div {
      height: 2000px;
    }

    p {
      height: 200px;
      background: red;
    }
  </style>
  
  <body>
  <div class="div"></div>

  <p id="p">我出现啦</p>
  
  <!-- 通过元素位置关系方法-->
  <script>
    function isContain(dom) {
      // 获取可视窗口的盖度。
      const screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
      // 获取滚动条滚动的高度
      const scrollTop = document.documentElement.scrollTop;
      // 获取元素偏移的高度。就是距离可视窗口的偏移量。
      const offsetTop = dom.offsetTop;
      return offsetTop - scrollTop <= screenHeight;
    }
    const p = document.getElementById("p");
    window.onscroll = () => {
      if (isContain(p)) {
        document.body.style.backgroundColor = 'blue'
      } else {
        document.body.style.backgroundColor = 'green'
      }
    }
  </script>

  <!-- 通过 getBoundingClientRect方法-->
  <script>
    // 只有当子元素全部出现在父元素中时,才会返回true。
    function isContain(dom) {
      const totalHeight = window.innerHeight || document.documentElement.clientHeight;
      const totalWidth = window.innerWidth || document.documentElement.clientWidth;
      // 当滚动条滚动时,top, left, bottom, right时刻会发生改变。
      const { top, right, bottom, left } = dom.getBoundingClientRect();
      console.log(top, right, bottom, left)
      return (top >= 0 && left >= 0 && right <= totalWidth && bottom <= totalHeight);
    }

    const p = document.getElementById("p");
    window.onscroll = () => {
      if (isContain(p)) {
        document.body.style.backgroundColor = 'blue'
      } else {
        document.body.style.backgroundColor = 'green'
      }
    }
  </script> 
  
  <!-- 通过new IntersectionObserver();  -->
  <script>
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        document.body.style.backgroundColor = "blue"
      } else {
        document.body.style.backgroundColor = "green"
      }
    }, { threshold: .2 });
    const p = document.getElementById("p")
    observer.observe(p)
  </script>
</body>

动画.gif