繁体   English   中英

隐藏/显示图像

[英]Hide/Show Image

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

但是由于某种原因,它不会切换可见/隐藏的图像。 关于我可能做错了什么的任何想法?

如果您仅使用类,则隐藏或显示任何内容会更直接。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM