梗概

  • 创建一个intersection观察者,并设定被用来比较的元素(默认是viewport
  • 用这个观察者去观察某个需要判断是否出现在可视区域的DOM元素
  • 在回调函数中可以判断这个元素是否出现在可视区域中

适用范围

优点

  • 性能更高,不用设定事件监听器去重复判断

实例

const intersectionObserver = new IntersectionObserver((entries) => {
  // If intersectionRatio is 0, the target is out of view
  // and we do not need to do anything.
  if (entries[0].intersectionRatio <= 0) return;
  console.log("Loaded new items");
});
// start observing
intersectionObserver.observe(document.querySelector(".scrollerFooter"));