Intersection Observer
1.介绍
Intersection Observer用于检测DOM元素在可视窗口中的位置,即可视性,可用于资源的预加载和延迟加载。于2016年11月29日,草案发布。兼容性,http://caniuse.com/#feat=intersectionobserver。
注:异步api,优先级不高
2.用法
var ele = document.getElementById("box"), ob = new IntersectionObserver( () => { console.log('触发了') }); ob.observe(ele);
2.1实例化对象的参数
2.1.1callback
1 var 2 ob = new IntersectionObserver( 3 changes => {
//changes为事件对象 4 for(const change of changes) { 5 // Timestamp when the change occurred 6 console.log(change.time); 7 // Unclipped area of root 8 console.log(change.rootBounds); 9 // target.boundingClientRect() 10 console.log(change.boundingClientRect); 11 // boundingClientRect, clipped by its containing block ancestors, and intersected with rootBounds 13 console.log(change.intersectionRect); 14 // Ratio of intersectionRect area to boundingClientRect area 15 console.log(change.intersectionRatio); 16 // the Element target 17 console.log(change.target); 18 } 19 });
2.1.2 配置项
threshold:数组,用于定义目标元素可视范围到达多少是触发回调。
root:父级容器,在哪个父级容器中滚动。
rootMargin:用于影响交叉区域的范围。
{
threshold: [0.25,1],
root: document.querySelector('body'),
rootMargin: "100px"
}
2.2实例化对象的方法
observer(ele):开始监听某个元素;
unobserver(ele):取消某个元素的监听;
disconnect():关闭观察器;
takeRecords(): 返回观察器的队列(数组),并清除当前队列。

浙公网安备 33010602011771号