DIV CSS 佈局教程網

用 jQuery 自定義 LoadImage:圖片超出容器自動等比縮放
編輯:JQuery特效代碼     

列表頁、產品牆、瀑布流……只要頁面上要展示尺寸不可控的用戶上傳圖,就繞不開「超框自動縮放」這個問題。下面是一個掛在 jQuery 原型上的 LoadImage 方法,兼顧等比縮放、加載動畫與緩存兼容。

完整實現

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.LoadImage = function(scaling, width, height, loadpic) {
    if (loadpic == null) loadpic = "../img/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);
                        }
                    }
                }
            }
        };

        // 處理 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();
        });
    });
};
</script>

頁面調用

<div id="content"><img src="img/20120518073933709.jpg"/></div>
<script type="text/javascript">
$(window).load(function() {
    $('#content img').LoadImage(true, 600, 500, 'img/loading.gif');
});
</script>

參數與實現思路

  • scaling:布爾開關,是否啟用自動縮放。
  • width / height:容器(目標框)的寬高。
  • loadpic:加載佔位圖路徑,默認 ../img/loading.gif。

縮放算法的核心是「比較寬高比」:先判斷原圖是偏寬還是偏高,再選定基準邊做等比計算,保證圖片永遠不變形。同時加了兩層保護——原圖本身就小於容器時保持原始尺寸,不做無意義的放大。

另一個容易忽略的細節是 img.complete 判斷。Firefox 在命中本地緩存時可能不會觸發 load 事件,導致加載動畫永遠轉圈、圖片永遠不顯示。提前檢測 complete 並直接執行縮放,能有效規避這個坑。

交互上先隱藏真圖、插入 loading 佔位圖,等 load 觸發後再移除佔位圖、還原 src 並顯示,視覺體驗會平滑很多。

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