萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現瀑布流佈局:浮動多列方案完整教學

jQuery 瀑布流佈局:浮動多列 + 無限滾動加載完整實現

瀑布流分為「絕對定位計算版」與「浮動多列版」。本文實現浮動多列方案:固定列數,新元素輪流追加到最短列,配合滾動加載,適合寬度固定、項目高度不一的場景。

兩大方案對比

方案原理優點缺點
絕對定位 JS 計算每項 top/left 對齊精確、支持動畫 計算複雜、響應式難、性能差
浮動多列 (本文) N 個浮動列,輪流 append 代碼簡單、CSS 自然流、易響應式 列高差大時底部不齊、難動畫

HTML/CSS 基礎結構

<style>
.wallList { width: 860px; margin: 0 auto; }
.wallList ul { list-style: none; margin: 0; padding: 0; }
.wallList li { 
  float: left; display: inline; width: 240px; margin-right: 16px; 
  margin-bottom: 10px; /* 關鍵:由內容撐開高度 */
}
.wallList li:nth-child(3n) { margin-right: 0; } /* 3列每行最後無間距 */
.wallList li a { 
  display: block; background: #eee; border: 1px solid #ccc; 
  padding: 5px 5px 0; text-decoration: none; color: #333;
}
.wallList li img { width: 100%; display: block; }
.wallList li .name { display: block; text-align: center; padding: 8px 0; }
.loadTips { text-align: center; padding: 15px 0; color: #666; }
.clearfix::after { content: ''; display: table; clear: both; }
</style>

<div class="wallList" id="wallList">
  <ul class="clearfix">
    <li></li><li></li><li></li>  <!-- 3 個空列佔位 -->
  </ul>
  <p class="loadTips" id="loadTips"><span>正在加載...</span></p>
</div>

核心 JS 邏輯

const Waterfall = {
  cols: 3,
  colHeight: [0, 0, 0], // 記錄每列高度
  loading: false,
  page: 1,
  
  init() {
    this.bindScroll();
    this.loadMore(); // 首屏加載
  },
  
  // 獲取最短列索引
  getMinColIndex() {
    return this.colHeight.indexOf(Math.min(...this.colHeight));
  },
  
  // 渲染單項
  renderItem(data, colIndex) {
    const $li = $(`
      
  • ${data.name} ${data.name}
  • `); // 追加到對應列 (li 是 ul 的直接子元素,需用 nth-child 選中列) // 技巧:用 3 個 ul 分別代表 3 列,或用 nth-child 選擇器 // 這裡演示:3 個獨立 ul 更簡單 $(`#wallList ul`).eq(colIndex).append($li); // 更新列高 (包含 margin-bottom) this.colHeight[colIndex] += data.height + 10; }, // 載入更多 loadMore() { if (this.loading) return; this.loading = true; $('#loadTips span').text('正在加載...'); // 模擬 Ajax setTimeout(() => { const mockData = this.generateMockData(9); // 每次 9 條 (3列×3行) if (mockData.length === 0) { $('#loadTips span').text('已加載完畢'); $(window).off('scroll', this.scrollHandler); return; } mockData.forEach((item, i) => { const col = i % this.cols; // 簡化:輪流分配,實際應用用 getMinColIndex this.renderItem(item, col); }); this.loading = false; $('#loadTips span').text('上拉加載更多'); this.page++; }, 500); }, // 滾動監聽 (節流) bindScroll() { let timer; this.scrollHandler = () => { clearTimeout(timer); timer = setTimeout(() => { const scrollTop = $(window).scrollTop(); const winH = $(window).height(); const docH = $(document).height(); // 距離底部 200px 觸發 if (scrollTop + winH > docH - 200) { this.loadMore(); } }, 100); }; $(window).on('scroll', this.scrollHandler); }, generateMockData(count) { // 實際項目替換為 $.getJSON('/api/images', { page: this.page }) const colors = ['B5E61D', '333', 'f60', '259', 'eee', '000']; return Array.from({ length: count }, (_, i) => ({ href: '#', src: `https://dummyimage.com/240x${200 + Math.random()*200}/${colors[Math.floor(Math.random()*colors.length)]}/fff`, width: 240, height: 200 + Math.floor(Math.random() * 200), name: `圖片 ${this.page * 9 + i + 1}` })); } }; // 初始化 $(function() { Waterfall.init(); });

    關鍵優化點

    1. 列高追蹤:用陣列記錄每列累計高度,O(1) 找到最短列
    2. 節流滾動:setTimeout 100ms 避免頻繁觸發
    3. 圖片尺寸預知:後端返回 width/height,避免圖片加載後佈局跳動
    4. 最小高度佔位:li { min-height: 200px; } 防止加載前塌陷
    5. 圖片懶加載:結合 loading="lazy" 或 IntersectionObserver

    響應式適配 (CSS 媒體查詢)

    @media (max-width: 900px) {
      .wallList { width: 100%; }
      .wallList li { width: calc(50% - 8px); } /* 2 列 */
      .wallList li:nth-child(2n) { margin-right: 0; }
      .wallList li:nth-child(3n) { margin-right: 16px; }
    }
    @media (max-width: 600px) {
      .wallList li { width: 100%; margin-right: 0; }
    }
    

    浮動多列方案代碼量極小、易維護,是中小型項目瀑布流的首選。

    copyright © 萬盛學電腦網 all rights reserved