I wanted to add a class to a collection of elements sequentially. I found an answer here.

For reference here is the code from that article:

var i = 0;
var callback;

callback = function () {
    if (i < article.length) {
       $(article[i]).addClass('something');

       ++i;
       setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);

I would now like to remove the class starting with the last element, so in effect reverse the order of what will be an animation.

Can anyone help? Many thanks in advance.

有帮助吗?

解决方案

Just start i as article.length loop in the other direction

var i = article.length;
var callback;

callback = function () {
    if (i--) {
       $(article[i]).removeClass('something');
       setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);

其他提示

Although the setTimeout method works, jQuery provides a way to achieve that far more elegantly:

$(".article").each(function() {
    var d = $(this);
    $("body").queue(function(next) {  
        d.addClass("foo");
        next();
    }).delay(200)
})

To iterate in reverse order, first add this small "plugin":

$.fn.reverse = [].reverse;

and then:

$(".article").reverse().each(function() {
    var d = $(this);
    $("body").queue(function(next) {  
        d.addClass("foo");
        next();
    }).delay(200)
})

To do reverse:

var i = article.length - 1;
var callback;

callback = function () {
    if (i >= 0) {
       $(article[i]).removeClass('something');

       --i;
       setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top