DIV CSS 佈局教程網

jQuery 圖片預載與等比縮放外掛實作教學
編輯:JQuery特效代碼     

圖片獨立在背景載入完成後才會顯示,畫面容易出現空白閃動;若再遇上尺寸不一的原始圖,版面也會被撐開。以下這個外掛一次解決兩件事:先預先載入圖片,再依容器尺寸等比縮放並垂直居中。

參數設計

  • scaling:是否啟用等比自動縮放。
  • width:允許的最大寬度。
  • height:允許的最大高度。
  • loadpic:載入期間顯示的佔位圖路徑,預設為 ../images/loading.gif。

呼叫方式: $("*").LoadImage(true, w, h);

核心程式碼

jQuery.fn.LoadImage = function(scaling, width, height, loadpic){
    if (loadpic == null) loadpic = "../images/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) return;
            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);
                    }
                }
                t.css("margin-top", (height - t.height()) / 2);
            }
        };

        // 處理 Firefox 直接讀取快取的情況
        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();
        });
    });
};

幾個實作細節

為什麼用 new Image()。瀏覽器快取行為不一致,某些情況下 complete 會立刻為 true,因此程式特別先做這個判斷,避免載入事件永遠不觸發。

縮放邏輯。以「圖片寬高比」與「容器寬高比」互相比較,決定該以寬度還是高度為基準收斂,確保圖片不會變形,也不會超出容器。

垂直居中。透過 margin-top 補上上下留白,讓不同高度的圖片在固定高度的容器裡視覺對齊,這在產品列表、相簿牆特別常見。

若要套用於大量圖片,建議搭配延遲載入(lazy load)一起使用,只載入視窗內的圖片,進一步降低首屏流量。

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