IntersectionObserver使用的几个注意点

吐槽君 分类:javascript

最近在使用IntersectionObserver时发现有几个需要注意的细节,这里记录整理一下,供大家参考。

本文所述的内容均不包括V2版本

关于IntersectionObserver的原理、使用方法、使用场景等方面的介绍,已经有相当多的文章涉及过了,本文就不再重复介绍了。

关于polyfill

我们都知道IntersectionObserver目前在iOS上的兼容是比较差的,只有12.1之后的版本才是原生支持的,显然是不符合兼容要求的(公司要求要兼容到iOS9),安卓还是OK的,5.0以上都原生支持了。因此如果要在移动端使用的话,需要引入polyfill,这里推荐w3c官方的polyfill,链接如下:
github.com/w3c/Interse…

rootMargin的值必须指定单位

rootMargin是用于扩展或者缩小rootBounds区域的大小,需要注意的是,rootMargin的值在设置的时候必须要带单位,否则就会导致observer无效,比如如下代码:

const observer = new IntersectionObserver(callback, {
  rootMargin: '100px 0'
})
 

这段代码就会导致页面报错,因为rootMargin的值必须指定单位,哪怕是0,单位可以是px,也可以是百分号。

这与css的margin属性其实是有差异的,因为如果是一个margin属性,同样按照上面的写法是OK的。

rootMargin负值

负的rootMargin可以将rootBounds的范围缩小,并且会影响交叉的触发,比如我们有如下的页面:

图片名称

布局非常简单:

.top-placeholder {
    height: 300px;
    background-color: aquamarine;
}
.content {
    height: 200px;
    background-color: blueviolet;
}
.bottom-placeholder {
    height: 1500px;
    background-color: cadetblue;
}
 

我们希望实现Content区域进入或离开视口顶部下方100px区域时触发一些操作,此时就可以利用负的rootMargin结合threshold实现

const callback = (entries) => {
    const { rootBounds, intersectionRatio } = entries[0];
    console.log(rootBounds, intersectionRatio);
};
const observer = new IntersectionObserver(callback , {
    threshold: [1],
    rootMargin: '-100px 0px 0px 0px'
});

observer.observe(document.querySelector('.content'));
 

rootMargin正值

基于上面的例子,我们在Bottom Placeholder下面增加一个Bottom Content区域,同样是一个简单的布局:

.bottom-content {
    height: 300px;
    background-color:chocolate;
}
 

初始进入页面时,Bottom Content区域是在视口之外的,并且距离视口还有一定的距离

此时我们希望实现Bottom Content区域进入视口底部下方100px区域时(也就是下图红色方框区域)做一些操作

图片名称

此时只需改写一下上面例子中的IntersectionObserver Options即可:

const observer = new IntersectionObserver(callback , {
    rootMargin: '0px 0px 100px 0px'
});
 

作者:掘金-IntersectionObserver使用的几个注意点

回复

我来回复
  • 暂无回复内容