jquery.waterFall.js
1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(function ($) {
$.fn.waterFall = function (options) {
// 默认值及参数
var defalut = $.extend({
gap: 20
}, options);
// 初始化
var _this = $(this),
items = _this.children(),
width = items.width(),
height = 0,
// 计算可以放置几列
count = Math.floor(_this.width() / (width + defalut.gap)),
columns = [];
items.each(function (key, val) {
// 每个元素的高度
height = $(val).height();
// 第一行
if(key < count) {
// 每一列的高度
columns[key] = height;
// 设置定位坐标
$(val).css({
top: 0,
left: (width + defalut.gap) * key
});
} else {
var min_h = columns[0];
var min_k = 0;
// 取出最小列及下标
for(var i=0; i<columns.length; i++) {
if(columns[i] < min_h) {
min_h = columns[i];
min_k = i;
}
}
// 更新当前列的高度
columns[min_k] += height;
$(val).css({
top: min_h + defalut.gap,
left: (width + defalut.gap) * min_k
});
}
});
// 最大值
var max_val = columns[0];
for(var j=0; j<columns.length; j++) {
if(columns[j] > max_val) {
max_val = columns[j];
}
}
_this.height(max_val);
}
})(jQuery);