IntersectionObserver API

IntersectionObserver API
可以自动”观察”元素是否可见,Chrome 51+ 已经支持。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做”交叉观察器”

1
2
3
4
let io = new IntersectionObserver(callback, option)
io.observe(element); // 开始观察
io.unobserve(element); // 停止观察
io.disconnect(); // 关闭观察器
callback

触发两次,标元素刚刚进入视口,另一次是完全离开视口

1
2
3
4
5
6
7
new IntersectionObserver(entries=>{
//entries is Array
entries.forEach(entry=>{
//entry IntersectionObserverEntry 对象
//...
})
})
IntersectionObserverEntry
  • boundingClientRect : 目标元素的矩形区域的信息
  • intersectionRatio : 目标元素与视口(或根元素)的交叉区域的信息
  • rootBounds:{width,height,left,right,bottom,top}
  • target: 目标元素,DOM 对象
  • time : 发生变化的时间,是一个高精度时间戳,单位为毫秒

image

options
  • threshold[Array] : 决定了什么时候触发回调函数,default:[0]
  • root:根元素
  • rootMargin:定义根元素的margin

应用场景

浏览器版本 Chrome 51+

eg. 惰性加载


eg. 无限加载(infinite scroll)

兼容性

参考资料