在 <img> 的 onload 事件中檢查實際寬高,超過上限時按比例縮放。關鍵點:只設寬度,高度自動等比(或兩者同步計算)。
<script>
function autoScaleImage(img, maxWidth = 690) {
// 確保圖片已完整載入(自然寬高可用)
if (img.naturalWidth === 0) return; // 尚未載入完成
if (img.naturalWidth > maxWidth) {
const ratio = maxWidth / img.naturalWidth;
img.width = maxWidth;
// img.height = img.naturalHeight * ratio; // 若 CSS 未設 height,瀏覽器會自動等比,此行可省略
}
// 移除 onload 避免重複觸發(動態換 src 時)
img.onload = null;
}
</script>
<img src="photo.jpg" onload="autoScaleImage(this, 690)" alt="示例圖片">
function autoScaleImageMax(img, maxWidth = 800, maxHeight = 600) {
if (img.naturalWidth === 0) return;
let {naturalWidth: w, naturalHeight: h} = img;
let ratio = 1;
if (w > maxWidth) ratio = Math.min(ratio, maxWidth / w);
if (h > maxHeight) ratio = Math.min(ratio, maxHeight / h);
if (ratio < 1) {
img.width = w * ratio;
img.height = h * ratio;
}
img.onload = null;
}
<style>
.img-responsive {
max-width: 100%; /* 不超過容器寬度 */
max-height: 600px; /* 可選:限制最大高度 */
height: auto; /* 關鍵:等比縮放 */
width: auto; /* 配合 max-width 使用 */
display: block; /* 去除底部縫隙 */
}
</style>
<img class="img-responsive" src="photo.jpg" alt="示例">
優點:無 JS 依賴、渲染更早、無閃爍、RWD 完美支援。
適用:現代專案首選,除非需在 JS 中取得縮放後尺寸做其他運算。
| 問題 | 原因 | 解決 |
|---|---|---|
| 圖片載入瞬間顯示原大小,隨後縮小(閃爍) | 瀏覽器先渲染原圖,JS 再調整 | 用 CSS 方案;或給 img 預設 style="max-width:690px; visibility:hidden;",onload 後 visibility:visible |
| 高度不按比例縮放 | CSS 同時設定 width 與 height 固定值 | 只設其一,另一用 auto |
naturalWidth 為 0 | 圖片尚未解碼完成 | 務必在 onload 內處理,或用 img.decode().then(...) (現代) |
動態換 src 後不觸發 onload | 瀏覽器快取導致瞬間完成 | 每次設 src 前先 img.onload = null; img.src = ''; 或加時間戳 src + '?t=' + Date.now() |
function autoScaleAndCallback(img, maxWidth, callback) {
img.onload = function() {
const ratio = Math.min(1, maxWidth / this.naturalWidth);
const finalW = this.naturalWidth * ratio;
const finalH = this.naturalHeight * ratio;
this.width = finalW;
this.height = finalH;
this.onload = null;
if (callback) callback(finalW, finalH, ratio);
};
}
// 使用
autoScaleAndCallback(document.getElementById('myImg'), 690, (w, h, r) => {
console.log(`縮放後:${w}x${h}, 比例 ${(r*100).toFixed(1)}%`);
});