频道
bg

IntersectionObserver

coding十二月 07, 20201mins
JavaScript Frontend

IntersectionObserver用来监听元素和和祖先或者或者顶级文档对象的交叉关系,或者更常见的是检测目标元素当前是否可见

处理函数

jsx

var intersectionObserver = new IntersectionObserver(function(entries) {
// If intersectionRatio is 0, the target is out of view
// and we do not need to do anything.
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
console.log('Loaded new items');
});

监听

jsx

// start observing
intersectionObserver.observe(document.querySelector('.scrollerFooter'));

触发函数会在初始化以为监听的元素的交叉状态发生变化时被调用,entries 传入的是交叉状态产生变化的元素,entries数据的顺序是按照当初被 observe() 的顺序排列的。

通过entry的isIntersecting 以及intersectionRatio 判断交叉的程度。

属性

  • root 可以修改被交叉的元素
  • rootMargin 可以给元素定义额外的虚拟边界,例如rootMargin: "50px, 0px" 会讲元素上下边界扩展50像素,这样元素还未正真可见时就会触发处理函数,实现预处理;又或者rootMargin: 0% 0% -80% 0% 定义的是元素的头上的20%的部分

参考H1

https://www.cnblogs.com/ziyunfei/p/5558712.html

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.