<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="box">
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
<img class="lazy" src="./img/loading.gif" data-src="./img/1.png" />
</div>
</body>
</html>
<script>
window.onload = function() {
// var imgs = document.querySelectorAll('.lazy')
var imgs = document.querySelectorAll('img')
function getTop(e) {
return e.offsetTop
}
function lazyLoad(imgs) {
var s = document.documentElement.scrollTop || document.body.scrollTop
var h = window.innerHeight
for(var i= 0;i<imgs.length;i++){
if(s+h>getTop(imgs[i])){
// console.log(1111)
(function(i){
setTimeout(function(){
var temp = new Image
temp.src = imgs[i].getAttribute('data-src');
temp.onload = function() {
imgs[i].src =imgs[i].getAttribute('data-src')
}
},2000)
})(i)
}
// var test = getTop(imgs[i])
// console.log('test',test)
}
}
lazyLoad(imgs)
window.onscroll =function() {
lazyLoad(imgs)
}
}
</script>
<style>
.box {
width: 200px;
display:flex;
flex-direction:column; // 改变主轴方向
justify-content:center; // 定义主轴的对齐方式
}
</style>