IntersectionObserver API用法

163 阅读1分钟

IntersectionObserver API

1.用法

是以new的形式声明一个对象,接收两个参数callbackoptions

const io = new IntersectionObserver(callback, options)

io.observe(DOM)
const options = {
  root: null,
  rootMargin: 0,
  thresholds: 1,
}
const io = new IntersectionObserver(entries => {
  console.log(entries)
  // Do something
}, options)

2.callback

callback是添加监听后,当监听目标发生滚动变化时触发的回调函数。接收一个参数entries,即IntersectionObserverEntry实例。描述了目标元素与root的交叉状态。具体参数如下:

属性说明
boundingClientRect返回包含目标元素的边界信息,返回结果与element.getBoundingClientRect() 相同
intersectionRatio返回目标元素出现在可视区的比例
intersectionRect用来描述root和目标元素的相交区域
isIntersecting返回一个布尔值,下列两种操作均会触发callback:1. 如果目标元素出现在root可视区,返回true。2. 如果从root可视区消失,返回false
rootBounds用来描述交叉区域观察者(intersection observer)中的根.
target目标元素:与根出现相交区域改变的元素 (Element)
time返回一个记录从 IntersectionObserver 的时间原点到交叉被触发的时间的时间戳
<!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>
    .box {
      height: 600px;
      overflow-y: scroll;
    }
    ul {
      padding: 0;
      margin: 0;
      list-style: none;
    }
    li {
      padding: 0;
      margin: 0;
      list-style: none;
      height: 100px;
      background-color: skyblue;
      width: 100px;
      text-align: center;
      margin-bottom: 20px;
    }
    .show-hide {
      width: 100%;
      height: 1px;
      line-height: 1px;
      z-index: 10;
      pointer-events: none;
      display: none;
      /* padding-bottom: 5px; */
    }
  </style>
</head>
<body>
  <div class="box">
    <ul class="list">
    </ul>
    <div class="show-hide"></div>
  </div>
  <script>
    let index = 0
    const showEl = document.querySelector('.show-hide')
    const list = document.querySelector('.list')
    setTimeout(() => {
      showEl.style.display = 'block'
    }, 10)
    const io = new IntersectionObserver(
      entries => {
        console.log('entries', entries[0].isIntersecting);
        if (entries?.[0].isIntersecting) {
          for (let i = 0; i < 20; i++) {
            const li = document.createElement('li')
            li.innerHTML = (index * 20 ) + i
            list.appendChild(li)
          }
          index++
          console.log('我来啦!', index);
        }
      }, {
        threshold: 0
      }
    )
    io.observe(showEl)
  </script>
</body>
</html>