如何使用按钮进行图像显示/隐藏

时间:2016-08-06 10:38:54

标签: javascript html image button

按下按钮时,我使用以下代码制作图像:

<html>
<head>
<title>Image Display Test</title>
<script type="text/javascript">
<!--
    function showImage(){
        document.getElementById('loadingImage').style.visibility="visible";
    }

-->
</script>
</head>
<body>
    <input type="button" value="Show Button" onclick="showImage();"/>
    <img id="loadingImage" src="pickups1.png" style="visibility:hidden"/>
</body>
</html>

到目前为止它仍然有效,但随后图像仍保留在屏幕上,无论如何,如果再次点击图像就会消失吗?

3 个答案:

答案 0 :(得分:1)

您可以检查图像是否可见,然后相应地隐藏/显示图像:

var elem = document.getElementById('loadingImage');
if (elem.style.visibility === 'visible') {
   elem.style.visibility = 'hidden';
} else {
   elem.style.visibility = 'visible';
}

或使用快捷方式(ternay运算符):

var elem = document.getElementById('loadingImage');
elem.style.visibility = elem.style.visibility === 'visible' ? 'hidden' : 'visible';

答案 1 :(得分:0)

试试此代码

<html>
<head>
<title>Image Display Test</title>
<script src="../js/jquery-1.7.2.js"></script>

<script type="text/javascript">
function showImage(){
    $('#loadingImage').toggle();
}
</script>
</head>
<body>
    <input type="button" value="Show Button" id="hide_show"  onclick="showImage();"/>
    <img id="loadingImage" src="1.jpeg"/>
</body>
</html>

答案 2 :(得分:0)

以下是一个工作示例:http://jsfiddle.net/rVBzt/

<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">

<a id="toggle">click to toggle</a>

img {display: none;}

a {cursor: pointer; color: blue;}

$('#toggle').click(function() {
    $('#tiger').toggle();
});