img {
max-width: 100%; /* 不超過容器寬度 */
height: auto; /* 關鍵:保持原始長寬比 */
}
適用於所有置換元素(img, video, canvas, svg, object...)。
.limit-800 { max-width: 800px; height: auto; }
.entry-content img {
max-width: 550px; /* 文章區最大寬度 */
width: expression(this.width > 550 ? '550px' : 'auto'); /* IE6/7 Hack */
height: auto;
}
注意:Expression 為 IE 專屬、效能差、安全風險,**新專案請勿使用**。
function autoFitImage(img, maxW, maxH) {
const image = new Image();
image.onload = () => {
let { width, height } = image;
if (width > maxW || height > maxH) {
const ratio = Math.min(maxW / width, maxH / height);
img.width = width * ratio;
img.height = height * ratio;
}
};
image.src = img.src;
img.style.cursor = 'zoom-in';
img.onclick = () => window.open(img.src, '_blank', 'width=800,height=600');
}
// 使用:
<picture>
<source media="(max-width: 480px)" srcset="img-480w.jpg">
<source media="(max-width: 800px)" srcset="img-800w.jpg">
<img src="img-1200w.jpg" alt="..." loading="lazy">
</picture>
loading="lazy" 原生延遲載入,提升首屏速度。