Why does this jquery slideToggle code not work?

我的未来我决定 提交于 2020-01-06 14:35:38

问题


I am trying to alter the button text for a expand/collapse button. Basically, a user clicks "Collapse" and I perform a slideToggle and when the slideToggle is done, I change the button text to "Expand" and vice-versa.

The following code works great however if you click the expand/collapse button rapidly, it looses its mind and shows "Expand" when it's already expanded or "Collapse" when it's already collapsed.

Any tips are appreciated.

Thanks!

function toggleBox( button, box ){ if($(box).is(":hidden")) { $(box).slideToggle("slow", function(){ $(button).html("Collapse"); }); } else { $(box).slideToggle("slow", function(){ $(button).html("Expand"); }); } }


回答1:


In your case, it'd be safer to do the check as you're setting the text, after the animation finishes, like this:

function toggleBox( button, box ){ 
  $(box).slideToggle("slow", function(){ 
    $(button).html($(this).is(":hidden") ? "Expand" : "Collapse"); 
  }); 
}

Currently you're checking when it starts, but remember it's not :hidden until it finishes hiding, so until the moment the slideUp completes, it's still :visible :)




回答2:


You can also try using

:not(:animated)


来源:https://stackoverflow.com/questions/2849398/why-does-this-jquery-slidetoggle-code-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!