萬盛學電腦網

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

jQuery 實現圖片等比例縮放兼容 IE6 的方案

問題背景

CSS max-width/max-height 在 IE6 不支援,導致大圖撐破容器。需用 JS 計算縮放比例並強制設置寬高。

jQuery 實現


$(function() {
    const $container = $('.imgBox');
    const maxWidth = $container.width(); // 容器最大寬度
    
    $('img').each(function() {
        const $img = $(this);
        
        // 等待圖片加載完成獲取真實尺寸
        $img.on('load', function() {
            // 兼容緩存情況下 load 不觸發
            if (this.complete) handleImage(this);
        }).each(function() {
            if (this.complete) handleImage(this);
        });
        
        function handleImage(img) {
            const imgWidth = img.naturalWidth || img.width;
            const imgHeight = img.naturalHeight || img.height;
            
            if (imgWidth > maxWidth) {
                const ratio = maxWidth / imgWidth;
                const newHeight = imgHeight * ratio;
                
                // IE6 需同時設置 width/height
                $(img).css({ width: maxWidth, height: newHeight });
            }
        }
    });
});

CSS 配合方案


.imgBox {
    width: 400px;           /* 最大寬度 */
    background: #ccc;
    text-align: center;
    line-height: 400px;     /* 垂直居中輔助 */
    font-size: 0;           /* 消除 inline-block 間隙 */
}

.imgBox img {
    max-width: 100%;        /* 現代瀏覽器自動縮放 */
    max-height: 400px;      /* 限制高度 */
    vertical-align: middle; /* 垂直居中 */
    border: none;
}

/* IE6 Hack */
* html .imgBox img {        /* 僅 IE6 識別 */
    width: expression(this.width > 400 ? "400px" : "auto");
    /* 注意:expression 性能差,不推薦生產環境大量使用 */
}

現代最佳實踐(無需 JS)


/* 容器限制 + 圖片自適應 */
.img-container {
    width: 400px;
    max-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.img-container img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;    /* 保持比例縮放 */
}

✅ 純 CSS、無 JS 依賴、支援響應式、現代瀏覽器全支援

進階:圖片懶加載 + 等比縮放


// IntersectionObserver 懶加載
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.onload = () => {
                img.classList.add('loaded');
                // 等比縮放邏輯(如需要)
            };
            observer.unobserve(img);
        }
    });
});

document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));

方案對比

方案IE6現代瀏覽器維護成本推薦
jQuery 計算縮放✅✅高舊項目維護
CSS expression✅❌高(性能差)❌
純 CSS max-width + flex❌✅極低✅ 新項目
object-fit❌✅極低✅ 新項目
copyright © 萬盛學電腦網 all rights reserved