瀑布流的核心是把內容分散到多個直向欄位中,讓高度較短的欄位優先接收下一筆內容,從而形成錯落有致的視覺排列。
下例以四個 flow 容器作為欄位,在頁面初始化與捲動到底部時,隨機產生不同高度的區塊,模擬瀑布流載入。
$(window).scroll(function () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
var pageHeight = $(document).height();
var viewHeight = $(window).height();
if ((scrollTop + viewHeight) > (pageHeight - 20)) {
$(".flow").each(function () {
$(this).append('<div style="height:' + getRandom(200, 300) + 'px"></div>');
});
}
});
實際專案可把隨機高度替換為真實資料高度,並加入載入中狀態、錯誤重試與分頁參數,提升穩定性。