onload 事件動態縮放圖片加載完成後,檢查寬度是否超過容器最大寬度,超過則等比縮放或限制最大寬度。
<script>
function limitImageWidth(img, maxWidth) {
// img: HTMLImageElement
// maxWidth: 數字,最大允許寬度(px)
if (img.naturalWidth > maxWidth) {
img.width = maxWidth; // 瀏覽器自動等比縮放高度
// 或顯式設置高度:img.height = img.naturalHeight * (maxWidth / img.naturalWidth);
}
}
// 用法:HTML 中直接綁定
// <img src="photo.jpg" onload="limitImageWidth(this, 500)">
// 批量處理頁面所有圖片
window.addEventListener('load', function() {
var images = document.querySelectorAll('img[data-max-width]');
images.forEach(function(img) {
var max = parseInt(img.dataset.maxWidth, 10);
if (!isNaN(max)) limitImageWidth(img, max);
});
});
</script>
<!-- HTML -->
<img src="large.jpg" data-max-width="500" alt="自動限寬 500px">
$(function() {
$('img[data-max-width]').each(function() {
var $img = $(this);
var max = parseInt($img.data('maxWidth'), 10);
// 圖片可能已緩存,onload 不觸發,需手動檢查 complete
if (this.complete) {
checkAndLimit(this, max);
} else {
$img.one('load', function() { checkAndLimit(this, max); });
}
});
function checkAndLimit(img, max) {
if (img.naturalWidth > max) {
$(img).css('width', max); // jQuery 自動處理單位
}
}
});
<style>
/* 1. 最大寬度限制,等比縮放 */
img.responsive {
max-width: 100%; /* 不超過父容器 */
height: auto; /* 等比縮放 */
display: block; /* 去除底部間隙 */
}
/* 2. 固定寬度容器內的圖片 */
.container {
width: 500px; /* 容器固定寬 */
}
.container img {
max-width: 100%;
height: auto;
}
/* 3. object-fit: cover/contain (固定尺寸框內裁剪/填充) */
.thumb {
width: 200px;
height: 200px;
overflow: hidden;
}
.thumb img {
width: 100%;
height: 100%;
object-fit: cover; /* 裁剪填滿 */
/* object-fit: contain; 完整顯示,留白 */
}
</style>
| 屬性 | 含義 | 可用時機 |
|---|---|---|
img.width / img.height | 顯示尺寸 (CSS/屬性設置後) | 隨時 |
img.naturalWidth / img.naturalHeight | 圖片原始像素尺寸 | onload 後 (或 complete=true) |
img.complete | 是否加載完成 (含緩存) | 隨時 |