萬盛學電腦網

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

jQuery 實現隨機圖片瀑布流無限載入:完整原理與程式碼解析

瀑布流佈局因 Pinterest、花瓣網等產品而大熱,核心邏輯是多欄等寬、高度自適應、動態追加、滾動觸發載入。本文提供一個基於 jQuery 的完整可執行範例,詳細拆解演算法步驟、關鍵 API 與效能優化方向。

核心演算法流程

  1. 初始化:建立 N 個等寬欄位(<ul class="col">),首輪隨機分配圖片。
  2. 尋找最短欄:每次新增圖片前,遍歷所有欄位找出 height() 最小者。
  3. 追加內容:將新圖片 append 至最短欄末尾。
  4. 滾動監聽:當 最短欄高度 ≤ 視窗滾動距離 + 視窗高度 時,觸發下一批載入。
  5. 循環:重複步驟 2-4 實現無限載入。

完整可執行範例(單檔版)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery 瀑布流無限載入 Demo</title>
  <style>
    *{margin:0;padding:0;box-sizing:border-box;}
    body{font:14px/1.5 system-ui,sans-serif;background:#f5f5f5;}
    #container{width:90%;max-width:1200px;margin:40px auto;}
    .col{width:32%;float:left;margin-right:2%;background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.08);overflow:hidden;}
    .col:last-child{margin-right:0;}
    .col li{list-style:none;padding:10px;}
    .col img{width:100%;height:auto;display:block;border-radius:4px;}
    .col p{margin:8px 0 0;font-size:12px;color:#666;text-align:center;}
  </style>
</head>
<body>
  <div id="container">
    <ul class="col"></ul>
    <ul class="col"></ul>
    <ul class="col"></ul>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
  <script>
  $(function () {
    const $cols = $('#container .col');
    const IMG_BASE = 'https://picsum.photos/seed/'; // 使用隨機圖片服務
    const LOAD_COUNT = 9; // 每輪載入張數

    // 取得目前最高度最小的欄位
    function getShortestCol() {
      let $min = $cols.eq(0);
      $cols.each(function () {
        if ($(this).height() < $min.height()) $min = $(this);
      });
      return $min;
    }

    // 載入一批圖片
    function loadBatch() {
      for (let i = 0; i < LOAD_COUNT; i++) {
        const seed = Math.floor(Math.random() * 1000);
        const $li = $('
  • ').appendTo(getShortestCol()); $('') .attr('src', `${IMG_BASE}${seed}/400/300`) .attr('alt', `Random ${seed}`) .on('load', function () { $(this).fadeIn(300); }) .on('error', function () { $(this).attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'); }) .appendTo($li); $('

    ').text(`seed: ${seed}`).appendTo($li); } } // 初始載入 loadBatch(); // 滾動觸發 let loading = false; $(window).on('scroll', function () { if (loading) return; const $minCol = getShortestCol(); const triggerPoint = $minCol.height(); const scrollBottom = $(window).scrollTop() + $(window).height(); if (triggerPoint <= scrollBottom + 200) { // 提前 200px 預載 loading = true; loadBatch(); // 模擬網路延遲,實際專案可在 AJAX complete 後釋放 setTimeout(() => loading = false, 300); } }); }); </script> </body> </html>

  • 關鍵技術點解析

    技術點實作細節優化建議
    最短欄查找遍歷 $cols 比較 height()欄數固定時可維護排序陣列,O(1) 取最小;或用 IntersectionObserver 替代 scroll 事件
    圖片載入完成後再計算高度img.onload 觸發預設圖片尺寸或 CSS aspect-ratio 佔位,避免佈局跳動
    防抖/節流loading 旗標 + setTimeout使用 lodash.throttle 或原生 requestAnimationFrame
    記憶體管理無限追加 DOM 節點虛擬滾動、移除可視區外節點、或分頁式載入

    現代化重構方向(無 jQuery 版)

    • 使用 IntersectionObserver 監測哨兵元素觸發載入,效能優於 scroll 事件。
    • 採用 CSS Grid / Flexbox + column-count 或 masonry (CSS Grid Level 3) 實現純 CSS 瀑布流(瀏覽器支援度逐漸提升)。
    • 圖片採用 loading="lazy" + srcset + sizes 原生懶載入與響應式。
    • 狀態管理用 React/Vue/Svelte 等框架,配合虛擬列表庫(react-window, vue-virtual-scroller)。

    結語

    瀑布流的核心不在於 jQuery,而在於「多欄最短優先」的佈局演算法與「滾動觸發載入」的無限滾動機制。理解原理後,無論用 jQuery、原生 JS 或現代框架,都能靈活實現。本文提供的單檔 Demo 可直接複製執行,建議在本地啟動靜態伺服器(如 npx serve 或 VS Code Live Server)體驗完整效果。

    copyright © 萬盛學電腦網 all rights reserved