jQuery delay between each toggleclass

匆匆过客 提交于 2020-01-30 11:17:06

问题


I have made a (rather complicated) solution where I have 4 menu items pop in/out from the side and I make that happen by toggling a class.

$('.menuitem').toggleClass('show');

It works great but the client now wants it to "slide out". I figured that I can make him happy if I can create a delay between each toggle, but I cant find a good way to do it. In practice I want each menu item to toggleClass but with a delay of maybe 250ms before next toggleClass.

Edited - Apparently the delay function wont work with toggle, only with animations.


回答1:


Consider this following code:

$('.menuitem').each(function(i) { 
    var elm=$(this);
    setTimeout(function() { 
        elm.toggleClass('show');
    }, i * 250); 
});

See it in action, in this demo i have hiding diving one by one and delay is 1000 ms.




回答2:


What about:

$('.menuitem').toggleClass('show').delay(1000).toggleClass('hide');

See jQuery's delay() function for further reference.




回答3:


I would do the $('.menuitem').toggleClass('show') in a separate event.

For instance <button onmousedown="$('.menuitem').toggleClass('show');" onclick="myfunc();">Fast Toggle</button>

If you toggle onmousedown the page will render with the toggle before the click event fires.



来源:https://stackoverflow.com/questions/33517695/jquery-delay-between-each-toggleclass

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