简体   繁体   English

如何使用javascript更改图像?

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

I expect my code to change the image.我希望我的代码能够更改图像。

I've made sure the script tag is correct.我已经确定脚本标签是正确的。

 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">

Error:错误:

Uncaught TypeError: Cannot set property 'src' of null未捕获的类型错误:无法将属性“src”设置为 null

Your script is most likely running before your HTML loads.您的脚本很可能在 HTML 加载之前运行。 Try putting your <script> tag at the bottom of the page, before your closing </body> :尝试将您的<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>

Not sure what issue, i reproduce it.不知道是什么问题,我重现了它。

May be you put script tag in head tag and img tag did not created.可能是您将 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">

Live example switching images:实时示例切换图像:

 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>


Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM