开发者

Temporarily Disallow JQuery Toggle

开发者 https://www.devze.com 2023-01-02 20:56 出处:网络
I have a menu that is toggled when a user selects a link. The menu had different show and hide animations attached, and I want to prevent toggling while the animation is running. The following snippet

I have a menu that is toggled when a user selects a link. The menu had different show and hide animations attached, and I want to prevent toggling while the animation is running. The following snippet works, but flips the state of toggle if the link is clicked quickly twice (i.e. if the user clicks the link quickly twice, the next click will trigger the same action):

<a href="" id="button">Menu</a>
<div id="menu">...</a>

<scrip开发者_Go百科t>
$("#button").toggle(
    function (e) { 
      if $("#menu").is(":animated")) return false;
      $("#menu").show("drop", {}, "slow"); 
    }, 
    function (e) { 
      if ("#menu").is(":animated")) return false;
      $("#menu").hide("bounce", {}, "slow"); 
    }
);
</script>

How can I prevent switching states within toggle?

Thanks.


Use .click(), and check the state of the element inside the click handler, using the :not(), :animated, and :visible selectors, like this:

$("#button").click(function () { 
  var menu = $("#menu:not(:animated)");
  if(menu.is(":visible")) menu.hide("bounce", {}, "slow");
  else menu.show("drop", {}, "slow"); 
});

This doesn't rely on the state, which is a bit simpler :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号