Html 如何在单击时更改图像并在单击时再次返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18009296/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:47:43  来源:igfitidea点击:

How to Change Image on click and get back again on clicking

htmlimagebutton

提问by SARAVANA KUMAR

I am Building a Javascript app

我正在构建一个 Javascript 应用程序

Now I want to have a image button that I have given already now I want to change the image to another image on clicking current image.

现在我想要一个我已经给出的图像按钮,我想在单击当前图像时将图像更改为另一个图像。

When i click again I want to get back the old image please any one help me by giving a coding example pls..

当我再次单击时,我想取回旧图像,请任何人通过提供编码示例来帮助我。

回答by Pirates

Try this:

尝试这个:

function diffImage(img) 
{
   if(img.src.match(/blank/)) img.src = "black.jpg";
   else img.src = "blank.jpg";
}

HTML

HTML

<img src="black.jpg" id="image1" onclick=diffImage(this) />

Just try to change image path as per your requirements or you can add multiple images.

只需尝试根据您的要求更改图像路径,或者您可以添加多个图像。

DEMO.

演示。

Hope this work.

希望这项工作。

回答by tannerwj

You could also do it with only using CSS if you wanted to.

如果你愿意,你也可以只使用 CSS 来做到这一点。

Just make a checkbox so you can click it without having to trigger an event and put the image in there and then have a different image for when it has been clicked.

只需创建一个复选框,这样您就可以单击它而不必触发事件并将图像放在那里,然后在单击时获得不同的图像。

<input type="checkbox"/>

And your CSS:

还有你的 CSS:

input[type="checkbox"] {
    content: url(image url here);
}
input[type="checkbox"]:checked {
    content: url(different image here);
}

I don't remember where I learned this trick, but it's worked for me in the past.

我不记得我从哪里学到了这个技巧,但它在过去对我有用。