瀑布流這種錯落有致的排布方式,視覺效果確實比齊頭式的網格活潑。它的核心邏輯並不複雜:每次都把新的項目放進目前最矮的那一欄。以下記錄完整實作。

<div class="wrapper">
<div class="items">
<div class="item"></div>
</div>
<p class="tips loading">正在加載...</p>
</div>
items 容器用來容放所有項目;tips 是載入更多資料時顯示給使用者看的提示文字。
body {
text-align: center;
margin: 0;
padding: 0;
background-color: #F7F7F7;
font-family: '微軟雅黑';
}
.wrapper { padding: 50px; }
img { display: block; width: 100%; height: 300px; }
.items {
position: relative; /* 關鍵:作為子元素的定位參考 */
padding-bottom: 10px;
}
.item {
width: 228px;
position: absolute; /* 關鍵:每個項目都絕對定位 */
border: 1px solid #ddd;
}
.tips {
width: 280px;
height: 40px;
margin: 30px auto 0;
text-align: center;
line-height: 40px;
background-color: #CCC;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
position: fixed;
bottom: 0px;
left: 50%;
margin-left: -140px;
opacity: 0; /* 平時隱藏,載入時才顯示 */
color: #666;
}
.tips.loading { background-color: #dadada; }
這裡有兩個關鍵設計:.items 設為 position: relative,讓內部元素的絕對定位以它為基準;.item 設為 position: absolute,這樣才能用 JS 精確指定每個項目的 left 與 top。瀑布流本質上就是手動計算座標。
由於所有項目的結構一致,這裡用 artTemplate 做模板渲染。使用前要先引入模板的 js 檔;模板 script 標籤需指定 id 與 type="text/html"。
<script src="../js/template_native.js"></script>
<script type="text/html" id="template">
<% for(var i = 0; i < items.length; i++){ %>
<div class='item'>
<img src="<%=items[i].path%>" alt="">
<p><%=items[i].text%></p>
</div>
<% } %>
</script>
function waterfall() {
var totalWidth = $(".items").width(); // 容器寬度
var eachWidth = $(".items .item").width(); // 單項寬度(皆相同)
var columNum = Math.floor(totalWidth / eachWidth); // 一行可放幾個
var margin = (totalWidth - eachWidth * columNum) / (columNum + 1);
// 初始化高度陣列,用來追蹤每一欄的當前高度
var heightArr = [];
for (var i = 0; i < columNum; i++) { heightArr[i] = 0; }
var elementItems = $(".items .item");
elementItems.each(function(idx, ele) {
// 找出目前最矮的那一欄
var minIndex = 0;
var minValue = heightArr[minIndex];
for (var i = 0; i < heightArr.length; i++) {
if (heightArr[i] < minValue) {
minIndex = i;
minValue = heightArr[i];
}
}
// 放到最矮處
$(ele).css({
left: margin + (margin + eachWidth) * minIndex,
top: minValue
});
// 更新該欄高度
heightArr[minIndex] += $(ele).height() + margin;
});
return heightArr;
}
這個函式的整個靈魂就在 heightArr 這個陣列。它記錄每一欄累積的高度,每放一個新項目就找出最小值所在的那一欄,把項目放上去,再把該欄高度加上這個項目的高度。如此反覆,視覺上就形成了參差但無空隙的排列。
$(function() {
$.ajax({
url: "./reset.php",
dataType: "json",
success: function(data) {
var result = template("template", { items: data });
$(".items").html(result);
waterfall();
}
});
});
$(window).on("scroll", function() {
if (toBottom()) {
$(".tips").css("opacity", 1);
$.ajax({
url: "./index.php",
dataType: "json",
success: function(data) {
var res = template("template", { items: data });
$(".items").append(res); // 注意是 append 而非 html
waterfall(); // 重新排版全部項目
$(".tips").css("opacity", 0);
}
});
}
});
function toBottom() {
var scrollTop = $(window).scrollTop();
var clientHeight = $(window).height();
var offsetTop = $(".items .item:last-child").offset().top;
return (scrollTop + clientHeight > offsetTop);
}
toBottom() 的判斷式很直觀:捲動距離加上視窗高度若已超過最後一個項目的頂部位置,就代表使用者看到接近底部了。
以下用 JSON 檔模擬資料,實際使用時替換成你的 API 即可。注意用這種方式取資料需要開啟本地伺服器。
// reset.php — 回傳初始資料
<?php
$jsonString = file_get_contents('info/reset.json');
$totalArr = json_decode($jsonString);
echo json_encode($totalArr);
?>
// index.php — 每次隨機回傳三筆
<?php
$jsonString = file_get_contents('info/data.json');
$totalArr = json_decode($jsonString);
$randomKeyArr = array_rand($totalArr, 3);
$templateArr = array();
for ($i = 0; $i < count($randomKeyArr); $i++) {
$currentKey = $randomKeyArr[$i];
$templateArr[$i] = $totalArr[$currentKey];
}
echo json_encode($templateArr);
?>
1. 圖片高度必須固定。範例的 CSS 把 img 高度寫死為 300px,這不是偷懶,而是必要條件。若圖片高度不固定,waterfall() 執行時圖片尚未載入完成,getElement().height() 會拿到 0,導致所有項目堆在一起。若必須使用變高圖片,得改用 Promise 等所有圖片 onload 之後再排版。
2. 必須有防重複請求的機制。目前寫法在捲動到底時每次 scroll 事件都會觸發一次請求,快速捲動會送出大量重複請求。加一個 isLoading 旗標即可:
let isLoading = false;
$(window).on("scroll", function() {
if (toBottom() && !isLoading) {
isLoading = true;
$.ajax({ /* ... */
complete: function() { isLoading = false; }
});
}
});
3. 需要終止條件。若後端已無更多資料,仍會持續請求。後端應回傳一個 hasMore 欄位,前端收到 false 就解除 scroll 監聽並顯示「沒有更多了」。
4. scroll 事件應做節流。每次捲動都執行 toBottom() 的 DOM 查詢成本不低。用 requestAnimationFrame 或 throttle 限制頻率是標準做法。
最後補充一點:現代 CSS 已有內建的 multi-column 與 grid 方案可以實現類似視覺效果,程式碼量遠低於手動計算。但那些方案在「item 順序沿欄填充」的行為上與瀑布流不同,若你需要嚴格控制項目的閱讀順序,手動定位仍是更可控的選擇。