jquery each add class with delay inbetween

前端 未结 3 799
鱼传尺愫
鱼传尺愫 2021-02-04 15:32

I need to loop through each div .row to add or remove a flip class that has a CSS3 3D transform effect.

When I apply this add/remove class to each \".row\" with jquery e

相关标签:
3条回答
  • 2021-02-04 16:07

    The jQuery delay() method only delays the next pieces in the queue of strung together methods using $(obj).delay(500).addClass('flip'); It doesn't delay all subsequent lines of code. (check out the first example and how the code runs its animations side-by-side)

    Try using setTimeout() instead.

    $('.row').each(function(i){
      var row = $(this);
      setTimeout(function() {
        row.toggleClass('flip');
      }, 500*i);
    });​
    

    Fiddle

    0 讨论(0)
  • 2021-02-04 16:17

    You have to use setTimeout to do a delay effect.

    Here is jsFiddle: http://jsfiddle.net/xQkmB/1/

    var i = 0;
    var rows = $(".row");
    show();
    
    function show() {
        if (i < rows.length) {
            $(rows[i]).show();
            i++;
            setTimeout(show, 1000);
        }       
    }
    
    0 讨论(0)
  • 2021-02-04 16:26

    The addClass function isn't an animation function, so it doesn't get queued, and so runs immediately without waiting for the .delay() to finish.

    I use this extension to queue non-animated jQuery calls:

    (function($) {
        $.fn.queued = function() {
            var self = this;
            var func = arguments[0];
            var args = [].slice.call(arguments, 1);
            return this.queue(function() {
                $.fn[func].apply(self, args).dequeue();
            });
        }
    }(jQuery));
    

    which in your code would be called thus:

    $('.row').each(function(i){
        $(this).delay(i*500).queued('toggleClass', 'flip');
    }
    

    NB: using toggleClass instead of a conditional add/remove.

    0 讨论(0)
提交回复
热议问题