1
我想知道是否有簡單的方法讓腳本在我的網頁上遍歷所有圖像(可能是某個類)並將所有這些圖像的源代碼更改爲相同的圖像。這是爲了一個復活節彩蛋,我想避免AJAX和jQuery等庫。JavaScript圖像替換
我想知道是否有簡單的方法讓腳本在我的網頁上遍歷所有圖像(可能是某個類)並將所有這些圖像的源代碼更改爲相同的圖像。這是爲了一個復活節彩蛋,我想避免AJAX和jQuery等庫。JavaScript圖像替換
你可以使用document.getElementsByTagName()
來獲取所有<img>
元素,像這樣:
var imgs = document.getElementsByTagName("img");
for(var i=0, l=imgs.length; i<l; i++) {
imgs[i].src = "someImage.jpg";
}
for (var i = 0; i < document.images.length; i++)
if (document.images[i].className == 'certain-class') // caution: can have multiple classes
document.images[i].src = '/hello.jpg';
document.images是從史前DOM0
投票,因爲`變種爲你我= 0,1 DOM2收養= imgs.length`,不知道那是行得通的。 – thejh 2010-11-28 17:54:28