用戶上傳圖片尺寸不一,頁面展示區域固定(如 120×120 縮圖),需**等比縮放**填滿或包含於容器,不變形、不裁切(或可選裁切)。
$(window).on('load', function () {
$('#gallery img').each(function () {
var $img = $(this);
var maxW = 120, maxH = 120;
var w = $img.width();
var h = $img.height();
// 圖片可能未就緒(緩存情況),load 事件確保 naturalWidth 可用
if (w === 0 || h === 0) return; // 防禦
var ratio = Math.min(maxW / w, maxH / h); // 包含模式
// var ratio = Math.max(maxW / w, maxH / h); // 覆蓋模式(需配合 overflow:hidden)
$img.css({ width: w * ratio, height: h * ratio });
});
});
$(window).on('load'):所有資源(含廣告、統計腳本)載入才觸發,延遲嚴重object-fit 一行解決<style>
.thumb {
width: 120px;
height: 120px;
object-fit: contain; /* 等比縮放,完整顯示,留白 */
/* object-fit: cover; /* 等比縮放,填滿容器,裁切 */
/* object-fit: fill; /* 拉伸填滿,變形 */
/* object-fit: none; /* 原尺寸 */
/* object-fit: scale-down; /* 取 none 或 contain 更小 */
background: #f0f0f0; /* 留白區域背景色 */
display: block;
}
</style>
<img src="any-size.jpg" class="thumb" alt="...">
object-fit 瀏覽器支援<div class="thumb-wrap">
<img src="..." class="thumb-img" alt="...">
</div>
<style>
.thumb-wrap {
width: 120px;
height: 120px;
overflow: hidden;
position: relative;
background: #f0f0f0;
}
.thumb-img {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
/* 等比縮放,居中顯示,超出容器裁切 */
}
</style>
// 只有在「需根據圖片原始比例動態決定容器尺寸」時才用 JS
function fitContainerToImage(img, maxW, maxH) {
return new Promise(function (resolve) {
var image = new Image();
image.onload = function () {
var ratio = Math.min(maxW / this.width, maxH / this.height);
resolve({ width: this.width * ratio, height: this.height * ratio });
};
image.src = img.src;
});
}
// 使用:動態調整容器尺寸
fitContainerToImage(document.querySelector('.dynamic-thumb img'), 300, 200)
.then(function (size) {
$('.dynamic-thumb').css(size);
});
function appendThumb(container, src, alt) {
var $wrap = $('').appendTo(container);
var $img = $('
').appendTo($wrap);
$img.on('load', function () {
$(this).addClass('loaded'); // 觸發 CSS 動畫
}).attr('src', src);
}
對比總結
方案 核心技術 優點 缺點 推薦場景
JS 計算縮放 width/height + onload IE 全支援 佈局抖動、load 事件慢、響應式難維護 極舊專案維護
CSS object-fit object-fit: contain/cover 零 JS、GPU 加速、響應式天然支援 IE 需 Polyfill **所有新專案首選**
CSS 絕對定位 + transform top/left/translate + max-width/height IE9+ 完美支援、無依賴 代碼稍多 需兼容 IE 且不想引 Polyfill
background-image + background-size background-size: contain/cover 語義非圖片、不可右鍵存圖 無障礙差、SEO 不友善 裝飾性圖標、Hero Banner
結語
**停止用 JS 計算圖片縮放**。CSS object-fit: contain/cover 結合 object-position 解決 99% 場景,效能更優、代碼更少、響應式天然適配。僅在「容器尺寸需根據圖片原始比例動態決定」這一極少數場景下,才在 onload 中讀取 naturalWidth/Height 計算一次。現代前端,樣式歸 CSS,邏輯歸 JS,各司其職。