jquery toggle - switch between toggle functions?

这一生的挚爱 提交于 2019-12-08 02:34:33

问题


hey guys, i love the jquery toggle function. however currently i'm facing a little issue where i don't know how to solve it in the best way.

i'm having a div called #searchbox which is depending on a user-setting either hidden or visible.

a toggle function that is triggered if i click on a button, should .slideDown() the #searchbox or .slideUp() the searchbox.

 //if already visible - slideDown
//if not visible - slideUp
$('#searchboxtrigger').toggle(
  function(){
    $('#searchbox').slideDown('fast');
  },
  function(){
    $('#searchbox').slideUp('fast');
  }
);

actually it works great already, only thing is that the first function inside toggle() always gets fired first, so if the #searchbox is already visible and slidedDown it should immediately trigger the slideUp function and vice versa.

any idea what i have to do to make that work?


回答1:


$('#searchboxtrigger').click( function(){
    $('#searchbox').slideToggle('fast');
  });



回答2:


Change your code to include stop()

Description: Stop the currently-running animation on the matched elements.

//if already visible - slideDown
//if not visible - slideUp
$('#searchboxtrigger').toggle(
  function(){
    $('#searchbox').stop(true).slideDown('fast');
  },
  function(){
    $('#searchbox').stop(true).slideUp('fast');
  }
);


来源:https://stackoverflow.com/questions/4121902/jquery-toggle-switch-between-toggle-functions

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