思路:监听网页的滚动事件,滚动时遍历查看图片是否在可视区域内,赋值图片的src
class lazyImg {
constructor(el) {
//将想要转换成数组的伪数组对象或可迭代对象 转换成数组
this.imgArr = Array.from(document.querySelectorAll(el));
this.init()
};
bindEvent() {
window.addEventListener('scroll',()=>{
this.main()
})
};
main() {
for (var i = 0; i < this.imgArr.length; i++) {
if (this.imgArr[i].getBoundingClientRect().top <= window.innerHeight) {
var temp = this.imgArr[i].getAttribute('data-src');
this.imgArr[i].src = temp;
//已加载过的从图片数组里删除掉,避免后面onscroll不必要的循环
this.imgArr.splice(i, 1);
i--;
}
}
};
init() {
this.main();
this.bindEvent();
}
}
new lazyImg('.list img')
网友评论