<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<img id="img" src="./img/loading.gif" img-src="./img/img1.jpg" alt="">
<img id="img" src="./img/loading.gif" img-src="./img/img2.jpg" alt="">
<img id="img" src="./img/loading.gif" img-src="./img/1.jpg" alt="">
<img id="img" src="./img/loading.gif" img-src="./img/2.jpg" alt="">
<img id="img" src="./img/loading.gif" img-src="./img/3.jpg" alt="">
</div>
</body>
<script>
function lazyLoad() {
// 1、 获取 页面 可视区域高度
var h = window.innerHeight;
// 2、 获取 滚动 高度
var y = window.scrollY;
// 3、获取所有图片
// var imgs=document.querySelectorAll("img");
var imgs = document.querySelectorAll("img");
for (let i = 0; i < imgs.length; i++) {
if (h + y > imgs[i].offsetTop) {
// console.log("图片"+i+"进入可视区域了")
setTimeout(function () {
imgs[i].src = imgs[i].getAttribute("img-src");
}, 2000)
}
}
}
lazyLoad();
window.onscroll = function () {
lazyLoad();
}
</script>
</html>
发表回复