跳到主要内容

IntersectionObserver API

· 阅读需 3 分钟

原来判断一个元素是否在页面显示区域中,需要使用scroll事件进行监听判断,现在有了IntersectionObserver就方便了很多。

用法为

var io = new IntersectionObserver(callback, option);

IntersectionObserver是浏览器原生提供的构造函数,接受两个参数:callback是可见性变化时的回调函数,option是配置对象(该参数可选)。

// 开始观察

io.observe(document.getElementById('example'));

// 停止观察

io.unobserve(element);

// 关闭观察器

io.disconnect();
var io = new IntersectionObserver(
entries => {
entries.forEach(i => {
console.log('Time: ' + i.time);
console.log('Target: ' + i.target);
console.log('IntersectionRatio: ' + i.intersectionRatio);
console.log('rootBounds: ' + i.rootBounds);
console.log(i.boundingClientRect);
console.log(i.intersectionRect);
console.log('================');
});
},
{
/* Using default options. Details below */
}
);
// Start observing an element
// 多次调用
io.observe(document.querySelector('#a'));
io.observe(document.querySelector('#b'));

返回的属性如下

time:可见性发生变化的时间,是一个高精度时间戳,单位为毫秒
target:被观察的目标元素,是一个 DOM 节点对象
rootBounds:根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回null
boundingClientRect:目标元素的矩形区域的信息
intersectionRect:目标元素与视口(或根元素)的交叉区域的信息
intersectionRatio:目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0

这里面返回的值里面有位置信息,就可以搞事情了。

看一下兼容性

虽然兼容还不是很好,要是这个方法主流兼容了就很好了。以后一定是一个好方法。

想要学习更多的请借一步前往阮大大这里看

http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html