Below is my javascript code which i used to show a div
when clicked on a button
.
How can I hide it when clicked again? And then on clicking it, div
should be visible again?
<script type="text/javascript">
var _hidediv = null;
function showdiv(id) {
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display = 'block';
_hidediv = function () { div.style.display = 'none'; };
}
</script>
In case you are interested in a jQuery soluton:
This is the HTML
<a id="button" href="#">Show/Hide</a>
<div id="item">Item</div>
This is the jQuery script
$( "#button" ).click(function() {
$( "#item" ).toggle();
});
You can see it working here:
If you don't know how to use jQuery, you have to use this line to load the library:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
And then use this line to start:
<script>
$(function() {
// code to fire once the library finishes downloading.
});
</script>
So for this case the final code would be this:
<script>
$(function() {
$( "#button" ).click(function() {
$( "#item" ).toggle();
});
});
</script>
Let me know if you need anything else
You can read more about jQuery here: http://jquery.com/
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
Try following logic:
<script type="text/javascript">
function showHideDiv(id) {
var e = document.getElementById(id);
if(e.style.display == null || e.style.display == "none") {
e.style.display = "block";
} else {
e.style.display = "none";
}
}
</script>
with JQuery .toggle()
you can accomplish it easily
$( ".target" ).toggle();
jQuery would be the easiest way if you want to use it, but this should work.
<script type="text/javascript">
function showHide(){
var e = document.getElementById('e');
if ( e.style.display != 'none' ) {
e.style.display = 'none';
}
else {
e.style.display = '';
}
}
</script>
来源:https://stackoverflow.com/questions/19074171/how-to-toggle-a-divs-visibility-by-using-a-button-click