IntersectionObserver API的使用教程
描述: 该API提供了可以在观察元素是否出现在视口当中的方法。
注: 可以同时监听多个目标元素是否出现的在视口当中
语法
var observer = new IntersectionObserver(callback[, options]);
使用步骤
第一步: 创建一个观察者(创建实例),当监听到指定目标元素出现在视口中,会执行指定的回调函数
该回调函数接受两个参数entries(一个[IntersectionObserverEntry]对象的数组)、observer(被调用的[IntersectionObserver]实例)
const callback=(entries,observer)=>{
entries.forEach(item)=>{
item.target //观察的目标元素,即进入或离开视口的元素。
item.isIntersecting// 是否满足交叉规则
item.intersectionRatio//目标元素与视口的相交比例,范围为0到1之间。当值为0时,目标元素完全离开视口;当值为1时,目标元素完全进入视口。
item.intersectionRect//目标元素与视口的相交区域的矩形信息,包括`x`、`y`、`width`和`height`四个属性。
item.boundingClientRect//目标元素的矩形信息,包括`x`、`y`、`width`和`height`四个属性。该矩形是相对于视口的,而不是相对于文档的。
item.rootBounds//根元素(即视口)的矩形信息,包括`x`、`y`、`width`和`height`四个属性。该矩形是相对于文档的
item.time //一个DOMHighResTimeStamp值,表示交叉发生的时间戳。
};
const options={};
const observers=new IntersectionObserver(callback,options) ;
//options的键值说明
options={
root:null,//指定根元素,默认值为null
rootMargin:0,//修改根元素的外边距
threshold:0,//目标元素与根元素交叉值,比如0.5(目标元素与根元素相交一半)
}
第二步: 把需要监测的目标元素传入实例方法observe中,就可以监测目标元素是否出现在视口当中
//获取目标元素
const el = document.getElementById('box');
observers.observe(el)
第三步: 根据回调函数中提供的字段来判读是否出现在根元素内部中
const observers=new IntersectionObserver((entries)=>{
entries.forEach(entry => {
if (entry.isIntersecting)
{ console.log('目标元素已进入视口'); }
else
{ console.log('目标元素已离开视口'); }
});
}) ;
实例方法
1、observers.disconnect
描述:该方法终止对所有目标元素可见性变化的观察
observers.disconnect();
2、observers.observe
描述:监测目标元素是否出现在视口中
observers.observe()
3、observers.unobserve
描述:停止对一个元素的观察
const el = document.getElementById('box');
observers.unobserve(el)
4、observers.takeRecords
描述: 返回一个 [IntersectionObserverEntry]对象数组,每个对象的目标元素都包含每次相交的信息,可以显式通过调用此方法或隐式地通过观察者的回调自动调用。
const intersectionObserverEntries=observers.takeRecords();