<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
main{
width: 800px;
margin: 0 auto;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-evenly;
}
main img{
width: 300px;
height: 300px;
margin: 10px 0;
}
</style>
</head>
<body>
<main>
<img src="" data-src="../../imgs/0.jpg">
<img src="" data-src="../../imgs/1.jpg">
<img src="" data-src="../../imgs/2.jpg">
<img src="" data-src="../../imgs/3.jpg">
<img src="" data-src="../../imgs/4.jpg">
<img src="" data-src="../../imgs/5.jpg">
<img src="" data-src="../../imgs/6.jpg">
<img src="" data-src="../../imgs/7.jpg">
<img src="" data-src="../../imgs/8.jpg">
<img src="" data-src="../../imgs/9.jpg">
<img src="" data-src="../../imgs/10.jpg">
<img src="" data-src="../../imgs/11.jpg">
<img src="" data-src="../../imgs/12.jpg">
<img src="" data-src="../../imgs/13.jpg">
<img src="" data-src="../../imgs/14.jpg">
<img src="" data-src="../../imgs/15.jpg">
<img src="" data-src="../../imgs/16.jpg">
<img src="" data-src="../../imgs/17.jpg">
<img src="" data-src="../../imgs/18.jpg">
<img src="" data-src="../../imgs/19.jpg">
<img src="" data-src="../../imgs/20.jpg">
</main>
<script>
function lazyImg(defaults=‘../../imgs/0.jpg‘){
//获取需要设置懒加载的图片元素
let lazyImgs=Array.from(document.querySelectorAll(‘img[data-src]‘)) ;
//设置默认图片
setDefaultImg();
//监听滚动事件
window.addEventListener(‘scroll‘,function(){
loadImgs();
})
//设置默认图片函数
function setDefaultImg(){
for(let i of lazyImgs){
i.src=defaults;
}
loadImgs();
}
//懒加载必要图片
function loadImgs(){
console.log(lazyImgs)
for(var i=0;i< lazyImgs.length;i++){
//检测当前位置
var img=lazyImgs[i];
if(loadImg(img)){
lazyImgs.splice(i,1);
i--;
}
}
console.log(lazyImgs)
}
//分析指定元素是否到达可视区域
function loadImg(img){
let position= img.getBoundingClientRect();
if(position.right>0&&position.left<document.documentElement.clientWidth&&
position.bottom>0&&position.top<document.documentElement.clientHeight){
img.src=img.dataset.src;
return true;
}
return false;
}
}
lazyImg();
</script>
</body>
</html>