<!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>
<img src="./image/loading.git" data-src="./images/1.jpg" alt="">
<img src="./image/loading.git" data-src="./images/2.jpg" alt="">
<img src="./image/loading.git" data-src="./images/3.jpg" alt="">
<img src="./image/loading.git" data-src="./images/4.jpg" alt="">
<img src="./image/loading.git" data-src="./images/5.jpg" alt="">
<img src="./image/loading.git" data-src="./images/6.jpg" alt="">
<img src="./image/loading.git" data-src="./images/7.jpg" alt="">
<img src="./image/loading.git" data-src="./images/8.jpg" alt="">
<img src="./image/loading.git" data-src="./images/9.jpg" alt="">
<img src="./image/loading.git" data-src="./images/10.jpg" alt="">
<img src="./image/loading.git" data-src="./images/1.jpg" alt="">
<img src="./image/loading.git" data-src="./images/2.jpg" alt="">
<script>
let num = document.getElementsByTagName('img').length
let img = document.getElementsByTagName('img')
let n = 0;
lazyLoad()
window.onscroll = lazyLoad;
function lazyLoad() {
//可视区域
let seeHeight = document.documentElement.clientHeight;
//滚动条距离顶部高度
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
for (let i = n; i < num; i++) {
if (img[i].offsetTop < seeHeight + scrollTop) {
if (img[i].getAttribute('src') == './image/loading.git') {
//替换
img[i].src = img[i].getAttribute('data-src')
}
n = i + 1
}
}
}
</script>
</body>
</html>
网友评论