換一張圖顯示,本質上就是改寫 img 元素的 src 屬性。一行程式就能完成,但其中有個容易忽略的細節:新圖會繼承舊圖的寬高。
<!DOCTYPE html>
<html>
<head>
<script>
function changeSrc() {
document.getElementById("myImage").src = "hackanm.gif";
}
</script>
</head>
<body>
<img id="myImage" src="compman.gif" width="107" height="98">
<br><br>
<input type="button" onclick="changeSrc()" value="Change image" />
<p><b>Note:</b> The src property can be changed at any time. However, the new image inherits
the height and width attributes of the original image, if no new height and width properties
are specified.</p>
</body>
</html>img 上的 width/height 屬性一旦設定,就會持續作用。換圖時若新圖的實際尺寸不同,會被強制拉伸或壓縮成舊尺寸,導致變形。三種解法:
var img = document.getElementById("myImage");
// 解法一:換圖的同時一併修改寬高
img.src = "new.png";
img.width = 200;
img.height = 150;
// 解法二:移除寬高,讓圖片以原始尺寸呈現
img.removeAttribute('width');
img.removeAttribute('height');
img.src = "new.png";
// 解法三:用 CSS 約束,不受單一圖片尺寸影響
// CSS: img { max-width: 100%; height: auto; }解法三最穩健,尤其在 RWD 情境下。height: auto 能確保寬度縮放時高度自動等比例調整。
指派 src 之後,圖片是非同步載入的,程式不會等它。若你需要在新圖載入完成後才做某件事,必須監聽 load 事件:
var img = document.getElementById("myImage");
img.addEventListener('load', function() {
console.log('新圖已載入', img.naturalWidth);
}, { once: true }); // 只觸發一次
img.src = "new.png";若忽略這一步,在新圖尚未載入前就讀取尺寸或做動畫,很可能拿到錯誤數值。
直接換 src 時,瀏覽器會先清空舊圖再載新圖,中間可能出現短暫空白。若要無閃爍切換,可先建立 Image 物件預載:
function switchImage(el, url) {
var preload = new Image();
preload.onload = function() {
el.src = url; // 已在快取中,幾乎瞬間完成
};
preload.src = url;
}指派給 src 的值可以是相對或絕對路徑。若讀取 img.src 屬性,瀏覽器會回傳完整絕對網址,即使你當初寫的是相對路徑。要取得原始寫法,用 img.getAttribute('src')。
最後提醒:src 的值若來自使用者輸入或外部資料,指派本身不會執行腳本(img 不執行 HTML),但仍應避免讓使用者能任意指定網域,否則可能成為外部內容嵌入或追蹤的途徑。