I want to toggle a div when pressing a button. Currently I have this:
$("#reportOptions").toggle("fast");
But when I first click the button, it sets the div to:
display: none;
And when I click again:
display: block;
Which is fine, but I want the first click to be style block, so the reverse the toggle.
How can I do this? Jquery.com does not explain this and every post on SO is about reversing the animations but not about the boolean.
I already tried to set the initial HTML to display: none;
but the animation cancels in a weird way (only for the first click) if I do it like that.
All toggle()
does is switch between display: none
and display: block
. If you want your first click to set the element to display: block
, initialize the element's style with display: none
. Here's a demo:
#reportOptionsHidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>Initially visible</h2> <div id="reportOptionsVisible">Here are the initially visible report options</div> <button onclick="$('#reportOptionsVisible').toggle('fast')">Toggle</button> <h2>Initially hidden</h2> <div id="reportOptionsHidden">Here are the initially hidden report options</div> <button onclick="$('#reportOptionsHidden').toggle('fast')">Toggle</button>
Toggle to hide and show can be use like this.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<div id="reportOptions" style="display:none;">
this is just test
</div>
<input type="button" onclick="fun_toggle()" value="Toggle">
<script type="text/javascript">
function fun_toggle(){
$("#reportOptions").toggle("hide");
}
</script>
只需以相反的显示启动CSS中的div,第一个切换按钮便会带您进入该显示。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.