DIV CSS 佈局教程網

JS動態修改圖片URL(src)的方法
編輯:關於JavaScript     

本文示範如何動態替換圖片,做法是改寫圖片元素的 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 not new height and width properties are specified.</p> </body> </html>

如範例最後一段所述,src 可以在任何時刻變更,但要注意:新圖片會沿用原圖的 height 與 width,除非你另行指定。這也是為什麼做圖片輪播或切換時,圖片常常被拉伸變形——記得同步更新尺寸,或乾脆只在 CSS 中固定寬高並加上 object-fit: cover。

另一個實務細節:新圖片載入完成前,舊圖仍會顯示,若網路較慢可能出現閃爍。若在意這個問題,可以先 new Image() 預先載入,等 onload 後再換上 src。

希望本文所述對大家的 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved