<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
margin: 0;
}
ul{
margin: 0;
padding: 0;
list-style: none;
}
img{
border: none;
vertical-align: middle;
}
.in{
border: 1px solid black;
margin: 10px;
text-align: center;
height: 400px;
width: 400px;
float: left;
}
.in img{
height: 400px;
width: 400px;
}
</style>
</head>
<body>
<ul class="list">
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
<li class="in"><img src="loading.svg" alt="测试" data-original = "pic.png"></li>
</ul>
<script>
function loadImg(arr){
for( var i = 0,len = arr.length; i < len; i++){
if(arr[i].getBoundingClientRect().top < document.documentElement.clientHeight && !arr[i].isLoad){
arr[i].isLoad = true;
arr[i].style.cssText = "transition: ''; opacity: 0;"
if(arr[i].dataset){
aftLoadImg(arr[i],arr[i].dataset.original);
}else{
aftLoadImg(arr[i],arr[i].getAttribute("data-original"));
}
(function(i){
setTimeout(function(){
arr[i].style.cssText = "transition: 1s; opacity: 1;"
},16)
})(i);
}
}
}
function aftLoadImg(obj,url){
var oImg = new Image();
oImg.onload = function(){
obj.src = oImg.src;
}
oImg.src = url;
}
var aImages = document.images;
loadImg(aImages);
window.onscroll = function(){
loadImg(aImages);
};
</script>
</body>
</html>
网友评论