// 基於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);
}