DIV CSS 佈局教程網

用 jQuery 打造等比例縮放圖片的實用插件
編輯:JQuery特效代碼     

在圖片展示場景中,經常需要讓圖片依容器尺寸等比例縮放,同時避免變形。這個自訂插件能自動判斷圖片與目標區域的寬高比,聰明地縮放到合適大小,還貼心地加入了載入中的過場提示。

插件原始碼

jQuery.fn.autoZoomLoadImage = function(scaling, width, height, loadPic) {
  if (loadPic == null) loadPic = "Loading.gif";
  return this.each(function() {
    var t = $(this);
    var src = $(this).attr("src");
    var img = new Image();
    img.src = src;
    // 自動縮放圖片
    var autoScaling = function() {
      if (scaling) {
        if (img.width > 0 && img.height > 0) {
          if (img.width / img.height >= width / height) {
            if (img.width > width) {
              t.width(width);
              t.height((img.height * width) / img.width);
            } else {
              t.width(img.width);
              t.height(img.height);
            }
          } else {
            if (img.height > height) {
              t.height(height);
              t.width((img.width * height) / img.height);
            } else {
              t.width(img.width);
              t.height(img.height);
            }
          }
        }
      }
    };
    // 處理 ff 下會自動讀取快取圖片的情況
    if (img.complete) {
      autoScaling();
      return;
    }
    $(this).attr("src", "");
    var loading = $("<img alt='加載中' title='圖片加載中' src='" + loadPic + "' />");
    t.hide();
    t.after(loading);
    $(img).load(function() {
      autoScaling();
      loading.remove();
      t.attr("src", this.src);
      t.show();
    });
  });
};

運作原理

插件的核心邏輯是先建立一個新的 Image 物件來預先載入圖片,取得真實的寬高後,再比較「圖片寬高比」與「目標區域寬高比」:

  • 若圖片較寬,就以目標寬度為基準等比例縮放高度。
  • 若圖片較高,則以目標高度為基準等比例縮放寬度。
  • 若圖片本身就小於目標區域,則保持原始尺寸,不放大導致模糊。

同時它會先隱藏原圖、顯示一張 Loading 提示圖,等圖片真正載入完成後再還原顯示,兼顧了使用者體驗。此外也特別處理了 Firefox 會自動讀取快取圖片的情況,避免縮放邏輯被跳過。

只要呼叫 $('img').autoZoomLoadImage(true, 200, 150),就能讓頁面上所有圖片依 200×150 的區域自動等比例縮放,非常適合產品列表、頭像牆等需要整齊排列的場合。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved