我想要实现图片懒加载,用getBoundingClientRect()获得相对于视口的位置
这个img的src应该为空才对,因为这张图片的位置处于视口外,可是它现在的src不是为空
在没有滑动滚动条的情况下
第一个数是图片的getBoundingClientRect().top
第二个数是视图的高
在滑动滚动条后,把滚动条滑到顶部,图片的getBoundingClientRect().top变正常了
let imgs = document.querySelectorAll('img')
fn()
window.onscroll = lazyload
function fn(){
let clientH = window.innerHeight
Array.from(imgs).forEach((item,index)=>{
let oBounding = item.getBoundingClientRect()
console.log(oBounding.top,clientH)
if(oBounding.top>0 && oBounding.top <= clientH ){
item.src = item.getAttribute('data-url')
}
})
}
let flat = true
function lazyload(){
if(flat){
flat = false
setTimeout(function(){
fn()
flat = true
},300)
}else{
return
}
}
单纯看你上面的代码没发现有什么问题,我前两天也实现了这个功能,也有用到这个,我是这样写的
<template>
<div>
<img v-for="(item,i) in lazyImgs" style="width: 180px;height:240px;margin-
top:40px;display: inline-block;" :data-src="item" :key="i" src="" v-lazy
alt="">
</div>
</template>
async mounted() {
window.addEventListener("scroll", (e) => {
// 这里做一个 节流 操作
if (this.timer) return;
this.timer = setTimeout(() => {
this.query("img[data-src]").forEach((img) => {
const rect = img.getBoundingClientRect();
if (rect.top < window.innerHeight) {
img.src = img.dataset.src;
// 我们是通过img[data-src]查找所有img标签的,渲染后就删除data-src可减少forEach循环的计算成本
img.removeAttribute("data-src");
}
});
clearTimeout(this.timer);
// 这里一定要把定时器置为 null
this.timer = null
}, 300);
});
}
你可以参考一下,另外我还用观察器实现了一版,可以进我主页博客看下,拿来就能用,没有问题