js实现仿百度瀑布流的方法
本文实例讲述了js实现仿百度瀑布流的方法。分享给大家供大家参考。具体实现方法如下:
<!DOCTYPEHTML>
<html>
<head>
<metacharset="utf-8">
<title>仿百度图片瀑布流</title>
<linkrel="stylesheet"type="text/css"href="style.css">
<scriptsrc="js/jquery.min.js"></script>
<style>
*{margin:0;padding:0;}
#container{
width:1000px;
border:1pxsolid#f00;
margin:50pxauto;
position:relative;
}
#containerimg{
position:absolute;
}
#loader{
width:100%;
height:60px;
background:url(loader.gif)no-repeatcenter;
position:fixed;
bottom:0;
left:0;
}
</style>
</head>
<scripttype="text/javascript">
$(function(){
varoContainer=$('#container');
varoLoader=$('#loader');
variWidth=200;//列宽
variSpace=10;//列数
variOuterWidth=iWidth+iSpace;
varsUrl='localhost/api/json/popular?callback=?';
variCell=0;
variPage=0;
vararrL=[];
vararrT=[];
variBtn=true;
functionsetCells(){
iCell=Math.floor($(window).innerWidth()/iOuterWidth);
if(iCell<3){
iCell=3;
}
if(iCell>6){
iCell=6;
}
oContainer.css('width',iOuterWidth*iCell-iSpace);
}
setCells();
for(vari=0;i<iCell;i++){
arrL.push(i*iOuterWidth);
arrT.push(0);
}
//console.log(arrL)
getData()
functiongetData(){
if(iBtn){
iBtn=false
oLoader.show();
$.getJSON(sUrl,'page='+iPage,function(data){
$.each(data,function(i,obj){
var$img=$('<img>');
$img.attr('src',obj.preview);
variHeight=iWidth/obj.width*obj.height;
varindex=getMin();
$img.appendTo(oContainer);
$img.css({width:iWidth,height:iHeight});
$img.css({top:arrT[index],left:arrL[index]})
arrT[index]+=iHeight+10;
oLoader.hide();
})
iPage++;
iBtn=true;
})
}
}
$(window).on('resize',function(){
variOldCell=iCell;
setCells();
variH=$(window).scrollTop()+$(window).innerHeight();
variMinIndex=getMin();
if(arrT[iMinIndex]+oContainer.offset().top<iH){
getData();
}
if(iOldCell==iCell)return;
arrT=[];
arrL=[];
for(vari=0;i<iCell;i++){
arrL.push(i*iOuterWidth);
arrT.push(0);
}
var$img=oContainer.find('img');
$img.each(function(index,obj){
varindex=getMin();
$(this).animate({top:arrT[index],left:arrL[index]})
arrT[index]+=$(this).height()+10;
})
})
$(window).on('scroll',function(){
variH=$(window).scrollTop()+$(window).innerHeight();
variMinIndex=getMin();
if(arrT[iMinIndex]+oContainer.offset().top<iH){
getData();
}
})
functiongetMin(){
variv=arrT[0];
var_index=0;
for(vari=0;i<arrT.length;i++){
if(arrT[i]<iv){
iv=arrT[i];
_index=i;
}
}
return_index;
}
})
</script>
<body>
<divid="top">仿百度图片瀑布流</div>
<!--标题e-->
<divid="container"></div>
<divid="loader"></div>
<!--效果块e-->
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。