IntersectionObserver 构造函数
用于检测某个元素是否进入视口(viewport),传统的方法是用 sroll 监听, 但是由于 sroll 事件会一直触发过于消耗性能。所以用一个新的Api intersectionObserver,可以自动观察元素是否可见,所以也称为“交叉观察器”
intersectionObserver 是原生浏览器提供的构造函数,
接收两个参数一个是callback,option
call是一个可见性变化时触发的回调函数,option是配置对象
var io = new IntersectionObserver(callback, option)
// 开始观察
io.observe(document.getElementById('example'))
// 停止观察
io.unobserve(element)
// 关闭观察器
io.disconnect()
如果多次调用
io.observe(elementA)
io.observe(elementB)
目标元素可见性变化时,就会调用 callback,一次时目标刚进入视口时触发(开始可见)
另外一次是离开视口(离开时可见)
var io = new IntersectionObserver((entries) => {
console.log(entries)
})
callback 函数的参数是一个数组,每个成员都是一个 IntersectionObserverEntry 对象。举例来说,如果同时有两个被观察的对象的可见性发生变化,entries 数组就会有两个成员
IntersectionObserverEntry的成员有以下几个:\
1. time : 可见性变化发生的时间是个时间戳,单位为毫秒;
2. target : 被观察的目标元素,是一个dom 节点对象;
3. isIntersecting : 目标是否可见;
4. rootBounds :根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回 null;
5. boundingClientRect :目标元素的矩形区域的信息;
6. intersectionRect :目标元素与视口(或根元素)的交叉区域的信息
7. intersectionRatio :目标元素的可见比例,即 intersectionRect 占 boundingClientRect 的比例,完全可见时为 1,完全不可见时小于等于 0
无限滚动
var intersectionObserver = new IntersectionObserver(function (entries) {
// 如果不可见,就返回
if (entries[0].intersectionRatio <= 0) return
loadItems(10)
console.log('Loaded new items')
})
// 开始观察
intersectionObserver.observe(document.querySelector('.scrollerFooter'))