html
<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background-color: red;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
   <script>
    // 创建一个IntersectionObserver实例
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 当目标元素进入视口时触发的回调函数
          entry.target.style.backgroundColor = 'green';
        } else {
          // 当目标元素离开视口时触发的回调函数
          entry.target.style.backgroundColor = 'red';
        }
      });
    });
     // 监听所有的.box元素
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => {
      observer.observe(box);
    });
  </script>
</body>
</html>
Last Updated:
Contributors: pengrengui