文章內容圖片寬度不一,超出容器寬度導致排版崩塌、橫向滾動條。需遍歷所有圖片,按比例縮放超寬圖片至最大允許寬度。
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 使用 |
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));
/* 容器限制最大寬度,圖片自適應 */
.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:瀏覽器根據設備像素比、視口寬度選擇最適合圖片max-width: 100%; height: auto; 解決 95% 場景window.load 後執行,確保 naturalWidth 可用dataset/data()) 避免重複計算MutationObserver 自動處理新增圖片