conan1992 / blog

记录下知识点..
3 stars 0 forks source link

图片懒加载 #49

Open conan1992 opened 4 years ago

conan1992 commented 4 years ago

clientHeight、scrollTop 和 offsetTop

getBoundingClientRect

if(imgs[i].getBoundingClientRect().top<viewHeight){
    console.log(i)
    imgs[i].src = imgs[i].getAttribute("data-src");
    count++;
}

var imgs = document.querySelectorAll("img");
var count = 0;
console.log(imgs)
var observer = new IntersectionObserver(function(entries){

    for(var i = 0; i<entries.length;i++){
        if(entries[i].isIntersecting){
            entries[i].target.src = entries[i].target.getAttribute("data-src");
            observer.unobserve( imgs[i] )
        }
    }
})
imgs.forEach(item => {
    observer.observe( item )
})

参考