隐藏/显示图像
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";
}
}
但由于某些原因,它没有切换可见/隐藏的图像。你知道我可能做错了什么吗?
如果使用类来控制样式,隐藏或显示任何内容都会更简单。
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" />
相关文章:
- 如何使用url加载程序在webpack中导入多个图像
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 角度:在ng重复上切换图像
- 画廊图像未显示
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- Javascript排序的图像弹出窗口..可以't单独弹出
- 画布数据到图像
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 使图像在单击时展开到不大于浏览器
- Html页面上的多个Base64图像和平滑加载
- UIAutomation放大图像
- 使用javascript在Flash中加载外部图像
- 可以在这里为背景图像设置滤镜吗
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 使用 js 将背景图像设置为 HTML
- Javascript将图像src更改为淡入淡出
- 无法在本地计算机中将画布另存为图像
- 压缩phonegap中ios的图像插件
- 如何在鼠标悬停时在另一个图像上滑动图像.