隐藏/显示图像

Hide/Show Image

本文关键字:图像 显示图 显示 隐藏      更新时间:2023-09-26

单击按钮时,我正试图隐藏/显示图像。我希望在这个小项目中只使用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>

^这就是HTML。

这是JavaScript:

function showOne() {
var img1 = document.getElementById("one");
img1.style.display = "";
  if(img1.style.display == "inline" ) {
    img1.style.display = "none";
  }
  else {
  img1.style.display = "inline";
  }
}

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

如果使用类来控制样式,隐藏或显示任何内容都会更简单。

document.getElementById('button').onclick = function () {
  document.getElementById('target').classList.toggle('show');
}
#target {
  display: none;
}
#target.show {
  display: block;
}
<input id="button" type="button" value="Toggle the image" />
<img id="target" src="http://i.imgur.com/a2F7iyp.jpg" alt="Picture of 1" />

在代码中,首先设置img1.style.display = "",然后检查它是inline还是none。此处始终为"",因此始终忽略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";
  }
}

我认为您可以简单地使用toggle()

JavaScript

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

HTML

<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" />