HTML 按钮更改图像源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8783984/
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
HTML Button Change Image Source
提问by user802609
Okay, I was wondering if this is possible. I want an image, and a totally separate button. When the button is clicked, I would like the Img Src to change from "images/test" to "images/test2"
好吧,我想知道这是否可能。我想要一个图像和一个完全独立的按钮。单击按钮时,我希望 Img Src 从“images/test”更改为“images/test2”
Is this possible?
这可能吗?
Let's just say I have a very simple site, with just an image and a button
假设我有一个非常简单的网站,只有一张图片和一个按钮
<html>
<head>...
</head>
<body>
<img src="images/test"/>
<br/><br/><br/>
<button>Click to change image!</button>
</body>
</html>
How can I change this very simple HTML to do what I want?
我怎样才能改变这个非常简单的 HTML 来做我想做的事?
回答by Murtaza
Firstly, your img
tag is not closed in your code.
Secondly, you can change the image src
on click of the button using simple javascript or jQuery.
首先,您的img
代码未在您的代码中关闭。其次,您可以src
使用简单的 javascript 或 jQuery 单击按钮更改图像。
<html>
<head>
<script>
function changeImage()
{
var img = document.getElementById("image");
img.src="images/test2";
return false;
}
</script>
</head>
<body>
<img id="image" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>