[英]Toggle between images in javascript
I'm trying to make a button, which toggles between 2 images, but I failed to. 我正在尝试制作一个在2张图片之间切换的按钮,但是我没有这样做。
This is my HTML: 这是我的HTML:
<img id="down" src="down.png">
<FORM>
<INPUT TYPE="button" VALUE="Pump" onclick="myFunction()" >
</FORM>
And this is the JavaScript: 这是JavaScript:
function myFunction()
{
if( document.getElementById("down").src == "down.png"){
document.getElementById("down").src = "1.png";
}
else if( document.getElementById("down").src == "1.png" ){
document.getElementById("down").src = "down.png";
}
}
How can I fix it? 我该如何解决?
The problem here is you are comparing just image name where your document.getElementById("down").src
gives you whole path including domain. 这里的问题是您只比较图像名称,而
document.getElementById("down").src
为您提供了包括域在内的整个路径。
You need to fetch image name from the src
您需要从
src
获取图像名称
function myFunction()
{
var source = document.getElementById("down").src; // get source
var imgName = source.substring(source.lastIndexOf('/') + 1); // fetch image name
if(imgName == "down.png"){ //check image name
document.getElementById("down").src = "1.png";
}
else if(imgName == "1.png" ){
document.getElementById("down").src = "down.png";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.