萬盛學電腦網

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

JavaScript 批量縮放頁面超大圖片:保持比例限制最大寬度

需求場景

文章內容圖片寬度不一,超出容器寬度導致排版崩塌、橫向滾動條。需遍歷所有圖片,按比例縮放超寬圖片至最大允許寬度。

原生 JavaScript 實現

function resizeImages(maxWidth = 600) {
    const images = document.images; // HTMLCollection,即時集合
    for (let i = 0; i < images.length; i++) {
        const img = images[i];
        // 僅處理未縮放、且寬度超標的圖片
        if (img.naturalWidth > maxWidth && !img.dataset.resized) {
            const ratio = maxWidth / img.naturalWidth;
            img.style.width = maxWidth + "px";
            img.style.height = (img.naturalHeight * ratio) + "px";
            img.dataset.resized = "true"; // 標記避免重複處理
        }
    }
}

// 頁面載入完成後執行
window.addEventListener("load", () => resizeImages(600));

// 動態載入內容後 (AJAX、無限滾動) 重新執行
// 可封裝為 MutationObserver 監聽容器變化
const observer = new MutationObserver(() => resizeImages(600));
observer.observe(document.getElementById("content"), { childList: true, subtree: true });

關鍵屬性解析

屬性含義備註
img.width / img.height顯示尺寸 (CSS 像素,受樣式影響)可寫,設置後會重繪
img.naturalWidth / img.naturalHeight圖片原始尺寸 (內在尺寸)只讀,圖片載入完成前為 0
img.complete圖片是否載入完成配合 onload 使用

jQuery 版本 (舊專案相容)

function resetImg(maxWidth = 600) {
    $("img").each(function() {
        const $img = $(this);
        if ($img.data("resized")) return; // 已處理
        // 確保圖片載入完成獲取自然尺寸
        if (this.complete) {
            process(this);
        } else {
            $img.one("load", () => process(this));
        }
    });

    function process(img) {
        if (img.naturalWidth > maxWidth) {
            const ratio = maxWidth / img.naturalWidth;
            $(img).css({ width: maxWidth, height: img.naturalHeight * ratio });
            $(img).data("resized", true);
        }
    }
}

$(window).on("load", () => resetImg(600));

CSS 替代方案 (無 JS、效能最優)

/* 容器限制最大寬度,圖片自適應 */
.content img {
    max-width: 100%;      /* 不超過父容器 */
    height: auto;         /* 保持比例 */
    display: block;       /* 消除底部間隙 */
}

/* 或限制絕對最大寬度 */
.content img {
    max-width: 600px;
    width: auto;
    height: auto;
}

優勢:零 JS、無重排、瀏覽器原生處理、響應式天然支援。唯一缺點:圖片原始尺寸巨大時仍會下載完整文件 (可配合 srcset/picture 響應式圖片解決)。

進階:響應式圖片完整方案

<picture>
  <source media="(max-width: 480px)" srcset="img-480w.webp" type="image/webp">
  <source media="(max-width: 768px)" srcset="img-768w.webp" type="image/webp">
  <source srcset="img-1200w.webp" type="image/webp">
  <img src="img-1200w.jpg" alt="描述" loading="lazy">
</picture>
  • loading="lazy":原生懶加載 (現代瀏覽器)
  • srcset + sizes:瀏覽器根據設備像素比、視口寬度選擇最適合圖片
  • WebP/AVIF 格式:體積減少 30-50%

總結建議

  1. 首選 CSS max-width: 100%; height: auto; 解決 95% 場景
  2. 舊專案、特殊約束 (如編輯器輸出固定寬高屬性) 再用 JS 修正
  3. JS 方案必須在 window.load 後執行,確保 naturalWidth 可用
  4. 標記已處理圖片 (dataset/data()) 避免重複計算
  5. 動態內容容器掛載 MutationObserver 自動處理新增圖片
copyright © 萬盛學電腦網 all rights reserved