HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- //<meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style lang="">
#lazy{width: 800px;margin: 0 auto;}
img{height: 500px;width: 500px;display:block;background: url(images/loading.gif) no-repeat center; margin: 100px auto;}
</style>
</head>
<body>
<div id="lazy">
<img data-src="images/1.jpg" src="images/pixel.gif"/>
<img data-src="images/2.jpg" src="images/pixel.gif"/>
<img data-src="images/3.jpg" src="images/pixel.gif"/>
<img data-src="images/4.jpg" src="images/pixel.gif"/>
<img data-src="images/5.jpg" src="images/pixel.gif"/>
<img data-src="images/6.jpg" src="images/pixel.gif"/>
</div>
</body>
<script src="./js/lazy.js"></script>
<script>
lazy({
id:"lazy",
lazyTime:1000,
lazyRange:1000
});
</script>
</html>
JS:
function lazy(arg){
//获取父级元素
var el = arg.id ? document.getElementById(arg.id) : document;
//判断id是否存在
if(el === null) return;
//获取所有的图片
var allImg = el.getElementsByTagName('img');
//所有图片的长度
allImgLen = allImg.length;
//定义一个空数组
imgArr = [];
//循环遍历
for(var i=0;i<allImgLen;i++){
var evImg = allImg[i];
//判断自定义属性data-src是否有值
if(evImg.getAttribute('data-src') !== null){
if(isLoad(evImg)){
setImg(evImg);
}else{
imgArr.push(evImg)
}
}
}
//判断当前屏幕的高度和图片距离顶部的距离,推出图片是否加载
function isLoad(el){
//获取滚动条的长度
var scrolltop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if(typeof el === 'undefined') return false;
//获取用户规定的长度值或者传入的参数长度值
var edit = ~~el.getAttribute('data-range') || arg.lazyRange;
//总的高度
var clientHeight = scrolltop + document.documentElement.clientHeight + edit
//定义一个图片距离顶部的初始值变量
var offsetTop = 0;
//el.tagName 返回的是大写的父级
while(el.tagName.toUpperCase() !== 'BODY'){
offsetTop += el.offsetTop
el = el.offsetParent
}
//返回true || false
return (clientHeight > offsetTop)
}
//把图片展示出来
function setImg(el){
el.src = el.getAttribute('data-src');
}
//判断图片是否已经加载过
function handler(){
for(var i=0,len=imgArr.length;i<len;i++){
var agoImg = imgArr[i]
if(isLoad(agoImg)){
_setTime(agoImg);
imgArr.splice(i,1);
len--;
if(len === 0){loadstop()}
}
}
}
window.addEventListener('scroll',handler,false);
//设置加载的时间
function _setTime(el){
if(arg.lazyTime){
setTimeout(function(){
setImg(el);
},arg.lazyTime + ~~el.getAttribute('data-time'));
}else{
setImg(el);
}
}
function loadstop(){
window.removeEventListener ? window.removeEventListener("scroll", handler, false) : window.detachEvent("onscroll", handler);
}
//loadstop();
window.addEventListener ? window.addEventListener("scroll", handler, false) : window.attachEvent("onscroll", handler);
}
网友评论