交叉观察器IntersectionObserver最简单demo

IntersectionObserver内部使用getBoundingClientRect与requestIdleCallback实现
接近与离开0.5都会执行,去除接近0.5的执行

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        margin: 0px;
        padding-top: 2000px;
      }
      #area {
        background-color: #aaa;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="area">IntersectionObserver区域</div>
    <script>
      let observer = new IntersectionObserver(
        (changes) => {
          changes.forEach((change) => {
            if (change.intersectionRatio < 0.5) return; //接近与离开0.5都会执行,去除接近0.5的执行
            console.log(`ratio`, change.intersectionRatio);
          });
        },
        { threshold: 0.5 }
      );
      observer.observe(window.area);
    </script>
  </body>
</html>
posted @ 2021-12-08 18:35  jerry-mengjie  阅读(73)  评论(0)    收藏  举报