需要批次處理頁面圖片時,例如做幻燈片、預先載入或統計數量,document.images 會比一個個寫 id 有效率得多。
這個集合會回傳文件中所有 Image 物件的參照,順序與原始碼中 <img> 出現的順序一致。要注意的是,為了與 0 級 DOM 保持相容,凡是透過 <object> 標籤定義的圖片,並不會被收進這個集合裡。
document.images
<html>
<body>
<img border="0" src="hackanm.gif" width="48" height="48">
<br />
<img border="0" src="compman.gif" width="107" height="98">
<br /><br />
<script type="text/javascript">
document.write("This document contains: ")
document.write(document.images.length + " images.")
</script>
</body>
</html>
頁面會輸出「This document contains: 2 images.」。
images[i].src = 'new.png' 即可動態替換圖片來源。src、alt、width、height、complete 等常用屬性。complete 與 naturalWidth 判斷圖片是否真的載入成功。for 迴圈,可一次為所有圖片掛上 onload 或 onerror。熟悉這個集合後,凡是與圖片相關的批次操作都能寫得簡潔許多。