原生js页面滚动延迟加载图片
本文实例为大家讲解了javascript瀑布流代码,即js页面滚动延迟加载图片,分享给大家供大家参考,具体代码如下
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>原生Js页面滚动延迟加载图片</title>
<styletype="text/css">
*
{
margin:0;
padding:0
}
img.scrollLoading
{
border:1pxsolid#ccc;
display:block;
margin-top:10px;
}
</style>
</head>
<body>
<divid="content"></div>
</body>
</html>
<scripttype="text/javascript">
var_CalF={
$:function(object){//选择器
if(object===undefined)return;
vargetArr=function(name,tagName,attr){
vartagName=tagName||'*',
eles=document.getElementsByTagName(tagName),
clas=(typeofdocument.body.style.maxHeight==="undefined")?"className":"class";//ie6
attr=attr||clas,
Arr=[];
for(vari=0;i<eles.length;i++){
if(eles[i].getAttribute(attr)==name){
Arr.push(eles[i]);
}
}
returnArr;
};
if(object.indexOf('#')===0){//#id
returndocument.getElementById(object.substring(1));
}
elseif(object.indexOf('.')===0){//.class
returngetArr(object.substring(1));
}
elseif(object.match(/=/g)){//attr=name
returngetArr(object.substring(object.search(/=/g)+1),null,object.substring(0,object.search(/=/g)));
}
elseif(object.match(/./g)){//tagName.className
returngetArr(object.split('.')[1],object.split('.')[0]);
}
},
getPosition:function(obj){//获取元素在页面里的位置和宽高
vartop=0,
left=0,
width=obj.offsetWidth,
height=obj.offsetHeight;
while(obj.offsetParent){
top+=obj.offsetTop;
left+=obj.offsetLeft;
obj=obj.offsetParent;
}
return{"top":top,"left":left,"width":width,"height":height};
}
};
//添加图片list
var_temp=[];
for(vari=1;i<21;i++){
_temp.push('<imgclass="scrollLoading"data-src="http://images.cnblogs.com/cnblogs_com/Darren_code/311197/o_'+i+'.jpg"src="http://images.cnitblog.com/blog/150659/201306/23160223-c81dd9aa9a2a4071a47b0ced2c9118bc.gif"/><br/>图片'+i);
}
_CalF.$("#content").innerHTML=_temp.join("");
functionscrollLoad(){
this.init.apply(this,arguments);
}
scrollLoad.prototype={
init:function(className){
varclassName="img."+className,
imgs=_CalF.$(className),
that=this;
this.imgs=imgs;
that.loadImg();
window.onscroll=function(){
that.time=setTimeout(function(){
that.loadImg();
},400);
}
},
loadImg:function(){
varimgs=this.imgs.reverse(),//获取数组翻转
len=imgs.length;
if(imgs.length===0){
clearTimeout(this.time);
return;
}
for(varj=len-1;j>=0;j--){//递减
varimg=imgs[j],
imgTop=_CalF.getPosition(img).top,
imgSrc=img.getAttribute("data-src"),
offsetPage=window.pageYOffset?window.pageYOffset:window.document.documentElement.scrollTop,//滚动条的top值
bodyHeight=document.documentElement.clientHeight;//body的高度
if((offsetPage+bodyHeight/2)>(imgTop-bodyHeight/2)){
img.src=imgSrc;
this.imgs.splice(j,1);
}
}
}
}
varimg1=newscrollLoad("scrollLoading");
</script>
希望本文所述对大家学习javascript程序设计有所帮助。