萬盛學電腦網

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

jQuery 圖片載入後自適應縮放:等比縮放、最大尺寸限制、CSS object-fit 現代替代

需求場景

用戶上傳圖片尺寸不一,頁面展示區域固定(如 120×120 縮圖),需**等比縮放**填滿或包含於容器,不變形、不裁切(或可選裁切)。

jQuery 計算縮放方案(傳統)

$(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'):所有資源(含廣告、統計腳本)載入才觸發,延遲嚴重
  • JS 計算 + 內聯樣式 → 佈局抖動、重排
  • 響應式斷點變化需重新計算
  • 無法處理動態插入圖片

現代最佳實踐:CSS 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 瀏覽器支援

  • Chrome 31+, Firefox 36+, Safari 10+, Edge 16+
  • IE 不支援 → object-fit-images Polyfill (3KB)

進階:容器自適應 + 圖片居中

<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 僅作兜底:獲取真實尺寸做決策

// 只有在「需根據圖片原始比例動態決定容器尺寸」時才用 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 = $('' + alt + '').appendTo($wrap); $img.on('load', function () { $(this).addClass('loaded'); // 觸發 CSS 動畫 }).attr('src', src); }

對比總結

方案核心技術優點缺點推薦場景
JS 計算縮放width/height + onloadIE 全支援佈局抖動、load 事件慢、響應式難維護極舊專案維護
CSS object-fitobject-fit: contain/cover零 JS、GPU 加速、響應式天然支援IE 需 Polyfill**所有新專案首選**
CSS 絕對定位 + transformtop/left/translate + max-width/heightIE9+ 完美支援、無依賴代碼稍多需兼容 IE 且不想引 Polyfill
background-image + background-sizebackground-size: contain/cover語義非圖片、不可右鍵存圖無障礙差、SEO 不友善裝飾性圖標、Hero Banner

結語

**停止用 JS 計算圖片縮放**。CSS object-fit: contain/cover 結合 object-position 解決 99% 場景,效能更優、代碼更少、響應式天然適配。僅在「容器尺寸需根據圖片原始比例動態決定」這一極少數場景下,才在 onload 中讀取 naturalWidth/Height 計算一次。現代前端,樣式歸 CSS,邏輯歸 JS,各司其職。

copyright © 萬盛學電腦網 all rights reserved