2019-12-11 seo達(dá)人
首先編寫一個(gè)簡單的容器:
<style>
width: 600px;
height: 100vh;
overflow-y: auto;
}
width: 100%;
}
width: 50%;
float: left;
margin: 20px 0;
list-style: none;
}
width: 200px;
height: 200px;
overflow: hidden;
margin: 0 auto;
border: 1px solid #999999;
}
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動(dòng)畫
let _image = new Image();
_image.src = './loading.gif';
//加載需要展示的圖片
let image = new Image();
image.src = src;
//加載成功,將loading圖片路徑改成對應(yīng)的真實(shí)路徑
image.onload = _ => image.src = .currentTarget.src;
//加載失敗,將loading圖片路徑改成默認(rèn)圖片路徑
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);
})
展示效果如圖:
每個(gè)圖片都是異步加載,加載完成后:
藍(lán)藍(lán)設(shè)計(jì)的小編 http://www.teruid.com