概述

Intersection Observer API 允许代码注册一个回调函数,该函数会在特定元素进入或离开与其他元素(或视口)的交点,或者两个元素之间的交点变化达到指定值时执行

用法

1
2
3
4
// callback 回调函数
// options 选项 {root: 监测的祖先元素 , rootMargin: 监测的祖先元素的边距(相当于css的margin区域) ,scrollMargin: 监测的祖先元素的滚动边距(相当于css的scroll-margin区域), threshold: 元素进入监测祖先元素的交点}
const observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector(".element"));