效果图如下:
如果是你想要的效果,请继续往下阅读…
项目结构图如下:
json数据如下:
![](https://i-blog.csdnimg.cn/blog_migrate/e1a8230e14fbc75128037cede3ad48ea.png)
话不多说,直接上代码:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片懒加载</title>
<link href="../css/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div class="photo" id="photo">
<img src="../image/loading.gif" class="lazyImg">
</div>
<script src="../js/index.js" type="text/javascript"></script>
</body>
</html>
在html文件中,该图片用于演示效果,为css做准备,后面将已经使用请求的数据将该图片覆盖,没有实际效果。
style.css
* {
padding: 0;
margin: 0;
}
.photo {
width: 600px;
margin: auto;
text-align: center;
}
.photo .lazyImg {
display: block;
width: 200px;
height: 200px;
margin: 5px;
}
css中,只是将图片大小,图片的容器div大小等进行了简单的设计。
重点部分
index.js
var jsonData = []; // 定义空数组,接收获取的图片数组
// 获取json中的数据
function getJson() {
var xhr = new XMLHttpRequest();
xhr.open('get', '../json/photo.json');
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var textSrc = '';
jsonData = jsonData.concat(JSON.parse(xhr.responseText)); // 将获取到的字符串转换成数组格式
for (var i = 0; i < jsonData.length; i++) {
textSrc += '<img src="../image/loading.gif" title="' + jsonData[i].photoTitle + '" class="lazyImg" data-src="' + jsonData[i].photoSrc + '">'
}
document.getElementById('photo').innerHTML = textSrc;
lazyLoad(photoList);// 调用懒加载方法
}
}
}
// 调用获取数据的方法
getJson();
//获取滚动条当前的位置
function getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
//获取当前可视范围的高度
function getClientHeight() {
var clientHeight = 0;
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
} else {
clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
}
return clientHeight;
}
//获取文档完整的高度
function getScrollHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
//获取元素距离顶部的位置
function getTop(e) {
return e.offsetTop;
}
// 图片懒加载方法
function lazyLoad(imgs) {
var viewHeight = getClientHeight();
var scrollHeight = getScrollTop();
var scrollTop = 0;
for (var i = 0; i < photoList.length; i++) {
scrollTop = getTop(imgs[i]);
if ((viewHeight + scrollHeight) > scrollTop) {
(function (i) {
setTimeout(function () {
var temp = new Image();
temp.src = imgs[i].getAttribute('data-src');
imgs[i].setAttribute('src', temp.src);
}, 300)
})(i)
}
}
}
//滚动事件触发
var photoList = document.getElementsByClassName('photo')[0].children;
window.onscroll = function () {
lazyLoad(photoList);
/* 下拉加载更多 */
if (getScrollTop() + getClientHeight() >= getScrollHeight() - 1) {
// 减1是防止获取的像素为小数,无法出现相等的情况
getJson();
}
};
还有什么问题都可以一起讨论。