;(function($){
$.fn.waterFall = function () {
var defultes = {
gap:15 ,//间距
}
defultes = $.extend(defultes);
var $this = $(this);
var item = $this.children();
// console.log(item);
var itemwidth = item.width();
var itemHeight = 0;
var itemarrayHeight = [];
var column = Math.floor($this.width()/itemwidth)
// console.log(column)
item.each(function (index,element) {
// console.log(index)
// console.log(element)
//获取第一行高度
itemHeight = $(element).height();
if(index < column){
$(element).css({
top:0,
left:(itemwidth+defultes.gap) * index
})
itemarrayHeight[index] = itemHeight;
}else{
var min_index = getMin(itemarrayHeight).index;
var min_value = getMin(itemarrayHeight).value;
// console.log(min_index)
// console.log(min_value)
$(element).css({
top:min_value+defultes.gap,
left:(itemwidth+defultes.gap) * min_index
})
itemarrayHeight[min_index] += itemHeight+defultes.gap;
}
// console.log(itemarrayHeight)
})
function getMin(arr) {
var min = {
};
min.index = 0;
min.value = arr[min.index];
for(var i=0;i<arr.length;i++){
if(arr[i] < min.value){
min.value = arr[i];
min.index = i;
}
}
return min;
}
function getMax(arr) {
var max = {
};
max.index = 0;
max.value = arr[max.index];
for(var i=0;i<arr.length;i++){
if(arr[i] > max.value){
max.value = arr[i];
max.index = i;
}
}
return max;
}
var max_value = getMax(itemarrayHeight).value;
$this.height(max_value);
}
})(jQuery)
使用
$(function(){
$(".items").waterFall();
})