繁体   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