The problem about jquery toggle function
First I write a pull down top menu in the html:
<div class="top-menu-contain">
<div class="pull-button" ><a href="#">Show Me</a></div>
<div class="pull-button"style="display: none;"><a href="#">Hide Me</a></div>
</div>
In default state ,the top menu at the top of the browser with "fixed" css property,and set the "top:-100px;",only show the pull button.Then I write the jquery code to achieve a effect that make the menu slide down:
$('.pull-button a').toggle(function () {
$('.top-menu-contain').animate({ top: '+=100px' }, 'slow');
}, function () {
$('.top-menu-contain').animate({ top: '-=100px' }, 'slow');
actully this work well, then I add a funtion that,when the menu slide down,the button could change from"Show Me" to "Hide Me",then I add this jquery code : $("div.pull-button").toggle(); So th开发者_C百科e total jquery code is:
$('.pull-button a').toggle(function () {
$('.top-menu-contain').animate({ top: '+=100px' }, 'slow');
$("div.pull-button").toggle();
}, function () {
$('.top-menu-contain').animate({ top: '-=100px' }, 'slow');
$("div.pull-button").toggle();
});
However it doesn't work right now, the button could change ,it become slide down twice,then slide up twice
here is the online case
So what wrong with my jquery code ?How can I achieve it in correct way?Thank you!
The problem is that you have two a
s here, which you're toggling between. What happens when you press the link is this:
- First click: First toggle block is executed for the first anchor.
- Second click: First toggle block is executed for the second anchor.
- Third click: Second toggle block is executed for the first anchor.
- Fourth click: Second toggle block is executed for the second anchor.
You can get around this by only using one anchor, and updating the text in it instead:
$('.pull-button a').toggle(function()
{
$('.top-menu-contain').animate({ top: '+=100px' }, 'slow');
$('div.pull-button > a').text("Hide Me");
}, function()
{
$('.top-menu-contain').animate({ top: '-=100px' }, 'slow');
$('div.pull-button > a').text("Show Me");
});
demo
jQuery
$('.pull-button a').toggle(function() {
$('.top-menu-contain').animate({
top: '+=100px'
}, 'slow');
$(this).text('Hide Me');
}, function() {
$('.top-menu-contain').animate({
top: '-=100px'
}, 'slow');
$(this).text('Show Me');
});
html
<div class="top-menu-contain">
<div class="pull-button" ><a href="#">Show Me</a></div>
</div>
精彩评论