共计 2060 个字符,预计需要花费 6 分钟才能阅读完成。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>LazyLoad</title>
<style>
img {
display: block;
margin: 0 auto 100px;
width: 680px;
height: 810px;
}
</style>
</head>
<body>
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-pl/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-bd/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cg/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cy/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-gb/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-mj/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-tm/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-wd/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cj/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-tc/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cy/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-sl/per.png"alt="">
<img src=""data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-qx/per.png"alt="">
</body>
<script>
var img = document.getElementsByTagName('img');
// 存储图片加载到的位置
var n = 0;
// 页面载入完毕加载可视区域内的图片
lazyLoad();
// 监听页面滚动事件
window.onscroll = lazyLoad;
function lazyLoad() {
// 可视区高度
//document.documentElement 返回的是文档对象 document 的根元素的只读属性 (如 html 元素)
var viewHeight = document.documentElement.clientHeight;
// 滚动条距离顶部的高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = n; i < img.length; i++) {if (img[i].offsetTop < viewHeight + scrollTop) {if (img[i].getAttribute('src') == '') {img[i].src = img[i].getAttribute('data-src');
}
n = i + 1;
}
}
}
</script>
</html>
搞清 clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop
正文完
发表至: javascript
2019-09-11