簡體   English   中英

如何使用javascript更改圖像?

[英]How do I change an image using javascript?

我希望我的代碼能夠更改圖像。

我已經確定腳本標簽是正確的。

 var x = document.getElementById("card_1_img"); x.src = "images/1.png"; //the error occurs here
 <img id="card_1_img" width="100" height="50">

錯誤:

未捕獲的類型錯誤:無法將屬性“src”設置為 null

您的腳本很可能在 HTML 加載之前運行。 嘗試將您的<script>標簽放在頁面底部,在您關閉</body>

 var x = document.getElementById("card_1_img"); x.src = "images/1.png";
 <body> <img id="card_1_img" width="100" height="50"> <script src="script.js"></script> </body>

不知道是什么問題,我重現了它。

可能是您將 script 標簽放在 head 標簽中,而沒有創建 img 標簽。

 var x = document.getElementById("card_1_img"); x.src = "https://hinhanhdephd.com/wp-content/uploads/2015/12/hinh-anh-dep-girl-xinh-hinh-nen-dep-gai-xinh.jpg";
 <img id="card_1_img" width="100" height="50">

實時示例切換圖像:

 let chromeImg = "https://www.w3schools.com/images/compatible_chrome.gif"; let firefoxImg = "https://www.w3schools.com/images/compatible_firefox.gif"; function change(browser) { let img = document.getElementById("browser"); let name = document.getElementById("name"); if (browser.src.includes("chrome")) { img.src = firefoxImg; name.textContent = "FireFox"; } else { img.src = chromeImg; name.textContent = "Chrome"; } }
 img, p { margin-left: 50px; }
 <h5>Click on image below:</h5> <img id="browser" onclick="change(this)" src="https://www.w3schools.com/images/compatible_chrome.gif"> <p id="name"></p>


參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM