<!DOCTYPE html>
<html>
<head>
<title>瀑布流布局</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
*{padding: 0;margin:0;}
#main{
position: relative;
}
.box{
/*paddin和margin,为了把盒子与盒子之间的距离拉开。因为在js中获取每个数据块的高度,offsetHeight可以获取包括padding在内的高度,而不能获取margin。*/
padding: 15px 0 0 15px;
float:left;
border:1px solid red;
}
.pic{
padding: 10px;
border:1px solid #ccc;
pic-shadow: 0 0 6px #ccc;
border-radius: 5px;
}
.pic img{
width:162px;
height:auto;
}
</style>
<script type="text/javascript">
window.onload=function(){
waterfall('main','box');
}
function waterfall(parent,box){
var oParent=document.getElementById(parent);
var oBoxs=getByClass(oParent,box);
var oBoxwidth=oBoxs[0].offsetWidth;
var winW=document.documentElement.clientWidth || document.body.clientWidth;
var cols=Math.floor(winW/oBoxwidth);
oParent.style.cssText="width:"+cols*oBoxwidth+"px;margin:0 auto;";
var picH=[];
for(var i=0,l=oBoxs.length;i<l;i++){
if(i<cols){
// 将图片的高度值添加到数组中
picH[i]=oBoxs[i].offsetHight;
}else{
// 求最小值和最小值的索引
var minH=Math.min.apply(null,picH);//注意必须有null
var minHindex=getMinhIndex(picH,minH);
// 计算及定义图片出现的位置
oBoxs[i].style.position='absolute';
oBoxs[i].style.top=minH+'px';
oBoxs[i].style.left=oBoxs[minHindex].offsetLeft+'px';
console.log(oBoxs[i].offsetLeft);
// 改变数组值
picH[minHindex]+=oBoxs[i].offsetHeight;
}
}
}
function getByClass(parent,clsName){
var boxArr=new Array(),
oElements=parent.getElementsByTagName('*');
for(var i=0;i<oElements.length;i++){
if(oElements[i].className==clsName){
boxArr.push(oElements[i]);
}
}
return boxArr;
}
// 求值在数组中的索引,arr接收的是数组,val接收的是判断的值
function getMinhIndex(arr,val){
for(var i in arr){
if(arr[i]==val){
return i;
}
}
}
</script>
</head>
<body>
<div id="main">
<div class="box">
<div class="pic">
<img src="images/0.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/1.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/2.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/3.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/4.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/5.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/6.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/7.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/8.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/9.jpg" />
</div>
</div>
<div class="box">
<div class="pic">
<img src="images/10.jpg" />
</div>
</div>
</div>
</body>
</html>