// 基于jquery的瀑布流插件css
$.fn.waterFall=function(option){jquery
//option 用户传过来的{gap:15}this
var defaluts={gap:20};
// 若是用户不传参数传递取默认值( 图片之间的间距)
defaluts=$.extend(defaluts,option);插件
var _this=$(this);// _this指的就是items 盒子图片
var allItem=_this.children('.item'); //获取了全部的item it
var itemWidth=allItem.width(); // 取第一个item的宽度io
var count=Math.floor(_this.width()/(itemWidth+defaluts.gap));console
// console.log(count);
//存储每一列的高度
var column=[]; function
//遍历全部的元素 给每一图片设置坐标值
//全部元素的left坐标 left= (item的宽度+defaults.gap)* index (列数-1)
//第一行的top为0
// 第一行以后的top值 不肯定
allItem.each(function(index,e){
//处理第一行
if(index<count){
//设置坐标值
$(e).css({
top:0,
left:(itemWidth+defaluts.gap)*index+'px'
});遍历
//记录当前每个列的高度
var height=$(e).height();
column[index]=height;
console.log(column);
}else{
//第二行如下图片的处理方式
////第二行如下 添加的规律:找最小列,往最小列的后面追加图片
//找出高度最小的列
var minHeight=column[0];
//记录最小的高度所在的列数 0-5
var minKey=0;
for(var i=0;i<column.length;i++){
if(minHeight>column[i]){
minHeight=column[i];
minKey=i;
}
}
var height=$(e).height();
$(e).css({
'top':minHeight+defaluts.gap+'px',
'left': minKey*(itemWidth+defaluts.gap)+'px'
});
//动态更新最小列的列高
column[minKey]+=height+defaluts.gap;
}
})
//找出最大的列高
var maxHeight=column[0];
for(var i=0;i<column.length;i++){
if(maxHeight<column[i]){
maxHeight=column[i];
}
}
//把itmes 设置高度
_this.height(maxHeight);
}