IntersectionObserver 异步检测目标元素和祖先元素或者viewport相交情况变化
用法
以new的形式声明,接受两个参数 callback options
const observer = new IntersectionOberver(callback,options)
observer.observe(DOM)
const options = {
root:null,
rootMargin:0,
thresholds:1,
}
const observer = new IntersectionOberver(entries=>{
console.log(entries)
},options)
observer.observe(DOM)
方法
callback
添加监听之后,当监听目标发生滚动变化时触发的回调函数。接受一个参数entries为IntersectionObserverEntry实例。描述了目标元素和root的交叉状态。具体参数:
比较常用的判断条件是 isIntersecting和intersectionRation
options
具体参数:
应用
图片懒加载
const imageList = [...document.querySelectorAll('img')]
cosnt observer = IntersectionObverser(entries=>{
entries.forEach(item=>{
if(item.isIntersecting){
item.target.src = item.target.dataset.src
observer.unobserve(item.target)
}
})
})
imageList.forEarch(img=>observer.observe(img))