javascript 在html中按下按钮时如何显示图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16624525/
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
How to display an image when pressing a button in html?
提问by user2279496
I thought doing something like this would have worked, but I'm confused as to why it isn't when the style is hiding the image to begin with, but not showing it when the button is pressed. Here's the code:
我认为做这样的事情会奏效,但我很困惑为什么当样式开始隐藏图像时它不是,但在按下按钮时不显示它。这是代码:
function showImg() {
x=document.getElementById("map_img")
x.style.visibility="visible";
}
<body>
<img id="map_img" src="map.jpg" style="visibility:hidden" width="400" height="400"/>
<form id="form1" name="form1" align="center">
<input type="submit" id="Map" value="Map" onclick="showImg()"/>
</form>
I've also tried this in both situations:
我也在两种情况下都尝试过:
<input type=button id="Map" value="Map" onclick="showImg()"/>
and:
和:
<style>
.hidden{display:none;}
.show{display:block;}
</style>
function showImg() {
x=document.getElementById("map_img")
x.class="show";
}
<body>
<img id="map_img" src="map.jpg" class="hide" width="400" height="400"/>
<form id="form1" name="form1" align="center">
<input type="submit" id="Map" value="Map" onclick="showImg()"/>
</form>
I'm really lost as to how neither of these worked, could I get some help on this please?
我真的不知道这两种方法是如何工作的,我能得到一些帮助吗?
采纳答案by DougM
You shouldn't* wrap the input
element in a form
if you don't want the standard submit behavior.
如果您不想要标准提交行为,则不应* 将input
元素包装在 a 中form
。
In your code as written, the form
triggers a page load or an error, which prevents the script from running.
在您编写的代码中,form
会触发页面加载或错误,从而阻止脚本运行。
回答by Klors
You don't really need the form on either of your examples.
你并不真正需要你的任何一个例子中的表格。
Your JavaScript should be in a <script>
block and you have a couple of syntax errors.
您的 JavaScript 应该在一个<script>
块中,并且您有几个语法错误。
Try
尝试
<head>
<script>
function showImg() {
document.getElementById("map_img").style.display = "";
}
</script>
</head>
<body>
<img id="map_img" src="map.jpg" style="display: none;" width="400" height="400"/>
<input type="submit" id="Map" value="Map" onclick="showImg()"/>
</body>
回答by Miro
DougM is right (+1)
DougM 是对的 (+1)
In addition it should be showImg = function()
另外应该是 showImg = function()
Here is a demo: http://jsfiddle.net/Uppt6/
这是一个演示:http: //jsfiddle.net/Uppt6/