首先编写一个简单的容器:
<style>
#content {
width: 600px;
height: 100vh;
overflow-y: auto;
}
#content ul {
width: 100%;
}
#content ul li {
width: 50%;
float: left;
margin: 20px 0;
list-style: none;
}
#content ul li p {
width: 200px;
height: 200px;
overflow: hidden;
margin: 0 auto;
border: 1px solid #999999;
}
#content ul li p img {
width: 100%;
display: block;
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
<div id="content">
<ul>
</ul>
</div>
然后,编写js代码:
let imageArr = [{
img_url: "http://www.lexilisi.com/Uploadpth/c45cc952-dcb7-493c-a171-357d1b820b37.png",
}, {
img_url: "http://xiaobanyou.com/static/images/xby_user_3.jpg",
}, {
img_url: "http://xiaobanyou.com/static/images/xby_user_4.jpg",
}, {
img_url: "http://xiaobanyou.com/static/images/xby_user_5.jpg",
}, {
img_url: "http://xiaobanyou.com/static/images/xby_user_6.jpg",
}, {
img_url: "http://xiaobanyou.com/static/images/xby_user_799.jpg",
}];
const lazyLoad = (src) => {
//加载loading动画
let _image = new Image();
_image.src = './loading.gif';
//加载需要展示的图片
let _image_ = new Image();
_image_.src = src;
//加载成功,将loading图片路径改成对应的真实路径
_image_.onload = _ => _image.src = _.currentTarget.src;
//加载失败,将loading图片路径改成默认图片路径
_image_.onerror = _ => _image.src = './error.png';
return _image;
}
let _content = document.getElementById('content');
let _ul = _content.getElementsByTagName('ul');
imageArr.forEach(value => {
let _li = document.createElement('li');
let _p = document.createElement('p');
let _image = lazyLoad(value.img_url);
_p.appendChild(_image);
_li.appendChild(_p);
_ul[0].appendChild(_li);
})
展示效果如图:
每个图片都是异步加载,加载完成后:
以上,希望对大家有所帮助。