Javascript 使用事件“onclick”更改图像源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34102091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing Images src with Event "onclick"
提问by MiguelC
<!DOCTYPE html>
<html>
<body>
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor()"/>
<script>
var image = document.getElementById("imageOne");
function changeColor() {
if (image.src == "circleRed.png") {
image.src = "circleBlue.png";
} else {
image.src = "circleRed.png";
}
}
</script>
</body>
</html>
This whole program may seem to work but no. I'll just be able to change the color of my image once. After clicking for the second time, nothing happens. What I mean is that I can only change the color from Red to Blue. Could you please help me figure out why?
整个程序可能看起来有效,但没有。我只能更改一次图像的颜色。第二次点击后,没有任何反应。我的意思是我只能将颜色从红色更改为蓝色。你能帮我找出原因吗?
采纳答案by Pramod Kumar
Here is the solution:
这是解决方案:
<!DOCTYPE html>
<html>
<body>
<img id ="imageOne" src ="circleRed.png" onclick = "changeColor()"/>
<script>
var image = document.getElementById("imageOne");
function changeColor()
{
if (image.getAttribute('src') == "circleRed.png")
{
image.src = "circleBlue.png";
}
else
{
image.src = "circleRed.png";
}
}
</script>
</body>
</html>
回答by Ibrahim Khan
image.src
returns the physical path of image. So you can use indexOf
to match image name. Following code snippet may help you.
image.src
返回图像的物理路径。所以你可以使用indexOf
来匹配图像名称。以下代码片段可能对您有所帮助。
function changeColor(image) {
if (image.src.indexOf("circleRed.png")>-1) {
image.src = "circleBlue.png";
} else {
image.src = "circleRed.png";
}
}
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>
回答by Hussein Hn
try this code. just make sure to use (img.src.match).And script inside the body.
试试这个代码。只要确保使用 (img.src.match)。和体内的脚本。
var img = document.getElementById("image1");
img.addEventListener("mouseover", function(){
if(img.src.match("images/image1.jpg")){
img.src ="images/image1_2.jpg";}
else {
img.src = "images/image1.jpg"
}
})
<img src="images/image1.jpg" id="image1" />
<img src="images/image1.jpg" id="image1" />
回答by Akshey Bhat
var image = document.getElementById("imageOne");
Move this inside function before if statement
在 if 语句之前移动这个内部函数