img.getBoundingClientRect().top - clientHeight < 0
// 节流
function fn(cb,delay=300){
let timer
return function(...args){
if(!timer){
cb.call(null,...args)
timer = setTimeout(()=>{
timer = null
},delay)
}
}
}
function imgLoad(){
const clientHeight = document.documentElement.clientHeight
const imgs = document.querySelectorAll("img[data-src]")
console.log(1, imgs[imgs.length-1].getBoundingClientRect().top - clientHeight );
for(img of imgs){
if(img.getBoundingClientRect().top - clientHeight < 0){
img.setAttribute('src', img.getAttribute('data-src'))
img.removeAttribute('data-src') // 移除属性,避免之后又被获取
}
}
}
const handleImgLoad = fn(imgLoad)
document.addEventListener('scroll',handleImgLoad)
Web为开发者提供了 IntersectionObserver 接口,它可以异步监听目标元素与其祖先或视窗的交叉状态,注意这个接口是异步的,它不随着目标元素的滚动同步触发,所以它并不会影响页面的滚动性能。
IntersectionObserver 实例执行回调函数时,会传递一个包含 IntersectionObserverEntry 对象的数组,该对象一共有七大属性: