Javascript 隐藏/显示图像

Javascript 隐藏/显示图像,javascript,html,css,Javascript,Html,Css,当您单击按钮时,我试图隐藏/显示图像。我只希望在这个小项目中使用JavaScript、CSS和HTML。到目前为止,我掌握的代码是: <span id = "one"> <img src = "1.png" alt = "Picture of 1" style="display: none;"/> </span> <input type="button" value="One" onclick="showOne();" /> <scrip

当您单击按钮时,我试图隐藏/显示图像。我只希望在这个小项目中使用JavaScript、CSS和HTML。到目前为止,我掌握的代码是:

<span id = "one">
<img src = "1.png" alt = "Picture of 1" style="display: none;"/>
</span>

<input type="button" value="One" onclick="showOne();" />

<script type = "text/javascript" src= "123clickJs.js">
</script>

但由于某些原因,它没有切换图像可见/隐藏。你知道我可能做错了什么吗?

在你的代码中,你首先设置img1.style.display=然后检查它是内联的还是无内联的。它总是在这里,所以if条件总是被忽略

请尝试以下方法:

function showOne() {
  var img1 = document.getElementById("one");
  if (!img1.style.display !== "none") {
    // If the image is displayed, whatever its style is, hide it
    img1.style.display = "none";
  } else {
    // Otherwise display it
    img1.style.display = "inline";
  }
}

如果只使用一个类,隐藏或显示任何内容都会更直接

oneButton.onclick=函数{ 一.类列表.切换'show'; } 一个{ 显示:无; } 一、表演{ 显示:块; }
我想你可以简单地使用切换键

JavaScript

$("#radio_btn").on("click", function () {
    $('.img_display').toggle();
});
HTML


您正在更改span的样式,但您的图像将始终隐藏,因为它有自己的内嵌-style@Overflow别傻了。没有必要为类似的内容加载库。@没错……但他仍然应该查看JQuery。而不是-target image:@Overflow不太需要。jQuery不像有些人想的那样,它不是Javascript库的终点。通常你甚至不需要一个图书馆,上面的问题就是一个很好的例子。对于那个否决我答案的人,请解释一下你认为它有什么问题。
$("#radio_btn").on("click", function () {
    $('.img_display').toggle();
});
<span id="one">
<img class="img_display" src = "http://www.monochrome-photo.info/home/nbigeast/monochrome-photo.info/public_html/wp-content/uploads/2012/10/1349454271_apple.png" alt = "Picture of 1" style="display: none;">
</span>

<input type="button" value="One" id="radio_btn" />