我们先获取图片到可视区顶部的距离,并获取到可视区的高度:
// html 部分
<style>
img {
display: block;
width: 100%;
height: 300px;
margin-bottom: 20px;
}
</style>
<div>
<img data-src="./images/1.jpg" alt="">
<img data-src="./images/2.jpg" alt="">
<img data-src="./images/3.jpg" alt="">
<img data-src="./images/4.jpg" alt="">
<img data-src="./images/5.jpg" alt="">
<img data-src="./images/6.jpg" alt="">
<img data-src="./images/7.jpg" alt="">
<img data-src="./images/8.jpg" alt="">
<img data-src="./images/9.jpg" alt="">
<img data-src="./images/10.jpg" alt="">
</div>
// js部分
// 图片列表
let images = document.querySelectorAll('img');
// 获取每张图片的垂直距离与视口的关系,并给img 设置src 属性
function setSrc(img) {
let bound = img.getBoundingClientRect();
let windHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
if(bound.top <= windHeight) {
img.src = img.getAttribute('data-src');
}
}
// 遍历给每个img赋值
function lazyLoad(images) {
for(let i = 0; i < images.length; i++) {
setSrc(images)
}
}
// 增加一个防抖函数,减少scroll触发频率
function debounce(func, wait, immediate) {
let timerId;
return function () {
const _this = this;
const args = arguments;
if(timerId) clearTimeout(timerId)
if(immediate) {
let callNow = !timerId;
timerId = setTimeout(function (){
timerId = null;
}, wait)
if(callNow) func.apply(_this,args);
} else {
timerId = setTimeout(function() {
func.apply(_this, args);
timerId = null;
}, wait)
}
}
}
// 给scroll绑定事件
window.addEventListener('scroll', debounce(function() {
lazyLoad(images);
}, 100))