自 Pinterest 爆紅之後,國內也掀起一陣「仿 PIN」熱潮,花瓣、蘑菇街等都是代表。瀑布流之所以受歡迎,是因為它能把長短不一的內容填滿每一吋版面,不留空白。市面上已有不少成熟方案,例如 jQuery 的 Masonry、KISSY 的 waterfall。本文則是動手用原生 JavaScript 實作一個簡易版本,不敢與上述優秀插件相提並論,但作為理解原理的練習,收穫往往比直接套用來得紮實。
瀑布流的算法其實只有一句話:把每一張卡片放進目前最矮的那一列。具體步驟是:
left = 索引 × 欄寬、top = 該欄目前高度。 .wf-main{ position: relative; margin: auto; width: 900px; overflow: hidden; }
.wf-main .wf-cld{
position: absolute; margin-bottom: 15px; padding: 10px 10px;
width: 180px; left: -999px; top: -999px; line-height: 20px;
border: 1px solid #e5e5e5; border-radius: 5px;
background-color: #fafafa; overflow: hidden;
}
.wf-cld .inner{
position: absolute; left: -999px; top: -999px; margin-bottom: 10px;
width: 160px; overflow: hidden;
border: 1px solid #fff; border-radius: 5px;
}
.wf-cld .title{ margin: 8px; padding: 5px; width: 160px; color: #666; font-size: 14px; }
所有卡片一律 position:absolute,並先推到 left:-999px 藏起來,等 JS 計算完位置再歸位,這樣可以閃掉初次載入時閃爍的問題。
<script type="text/javascript">
function Waterfall(param){
this.id = typeof param.container == 'string'
? document.getElementById(param.container) : param.container;
this.colWidth = param.colWidth;
this.colCount = param.colCount || 4;
this.cls = param.cls && param.cls != '' ? param.cls : 'wf-cld';
this.init();
}
Waterfall.prototype = {
// 以 className 取得元素集合
getByClass: function(cls, p){
var arr = [], reg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", "g");
var nodes = p.getElementsByTagName("*"), len = nodes.length;
for(var i = 0; i < len; i++){
if(reg.test(nodes[i].className)){
arr.push(nodes[i]);
reg.lastIndex = 0;
}
}
return arr;
},
maxArr: function(arr){
var len = arr.length, temp = arr[0];
for(var ii = 1; ii < len; ii++){
if(temp < arr[ii]){ temp = arr[ii]; }
}
return temp;
},
// 取得 margin-bottom,相容 IE 的 currentStyle
getMar: function(node){
var dis = 0;
if(node.currentStyle){
dis = parseInt(node.currentStyle.marginBottom);
}else if(document.defaultView){
dis = parseInt(document.defaultView.getComputedStyle(node, null).marginBottom);
}
return dis;
},
// 找出目前最矮的欄,回傳其索引
getMinCol: function(arr){
var ca = arr, cl = ca.length, temp = ca[0], minc = 0;
for(var ci = 1; ci < cl; ci++){
if(temp > ca[ci]){ temp = ca[ci]; minc = ci; }
}
return minc;
},
init: function(){
var _this = this;
var col = []; // 各欄目前高度
var nodes = _this.getByClass(_this.cls, _this.id), len = nodes.length;
for(var i = 0; i < _this.colCount; i++){ col[i] = 0; }
// 先量出每張卡片的高度(含 margin)
for(var i = 0; i < len; i++){
nodes[i].h = nodes[i].offsetHeight + _this.getMar(nodes[i]);
}
// 依序放入最矮的欄
for(var i = 0; i < len; i++){
var ming = _this.getMinCol(col);
nodes[i].style.left = ming * _this.colWidth + "px";
nodes[i].style.top = col[ming] + "px";
col[ming] += nodes[i].h;
}
_this.id.style.height = _this.maxArr(col) + "px";
}
};
// 巢狀的內部瀑布流
new Waterfall({ "container":"wf-inner", "colWidth":170, "colCount":3, "cls":"inner" });
// 外層瀑布流
new Waterfall({ "container":"wf-main", "colWidth":200, "colCount":4 });
</script>
HTML 部分只需要一個外層容器 .wf-main,裡面放任意數量的 .wf-cld 卡片即可;範例中還刻意在其中一張卡片內嵌 #wf-inner,用來示範同一套類別可以同時驅動多個巢狀瀑布流,這也是把它寫成建構式物件的用意。
運行結果如下:

這個版本刻意保持簡單,因此仍有幾個實務上必須補齊的環節:視窗 resize 時要重新排版、圖片載入完成後高度會改變所以需監聽 load、以及若要支援動態插入內容則需對外暴露一個 render() 方法。把這幾點補上,基本就能在中小規模的頁面裡直接使用;若欄數多、卡片上千,還是建議改用 Masonry 這類經過高度最佳化的方案。