开发者

How to animate a set of jQuery objects one at a time (instead of all at once)

I'm trying to build a picture slider. (I know there are tons of plug-ins out there, but this is more for educational purposes).

Basically, I have a set of images with z-index: 0. What I am 开发者_如何学Gotrying to do is take the set of images, then select each one of the images and change the index to 1, animate the opacity, and then put it back at 0, so that the next image will do the same thing.

This is the first part, but the problem I have is that when I am testing this part, all the images do the animation at the same time. Instead of doing one after the other. I know that you can use callback functions such as:

image1.animate(the animation, function({
       image2.animation(the animation, function({
                image3.animation(the animation, function}) etc...

})

But if I had more images it would become more complicated. I am trying to find a more efficient way of doing this, but I am not finding the answer.

This is what I have tried:

images.each(function () {
    $(this).css({
        "opacity" : "0.0",
        "z-index" : "1"
    }).animate({
        opacity: "1.0"
    }, 3000);
});

but it doesn't work. All the images do the animation at the same time. I even tried with a "for" loop, but I get the same thing:

for (var i=0; i<images.length; i++){
    images.eq(i).css({
        "opacity" : "0.0",
        "z-index" : "1"
    }).animate({
        opacity: "1.0"
    }, 3000);
}

I know I am doing something wrong, but I can't figure out what it is. If anyone has any help it would be greatly appreciated!


Use a .delay(), like this:

images.each(function (i) {
    $(this).delay(3000*i)
           .css({ opacity : 0, "z-index": 1 })
           .animate({ opacity: 1 }, 3000);
});

Since this uses the index of the element passed as the first parameter to the .each() callback the first is delayed 3000*0ms, so not at all, the second delays for 3000ms, etc...so they animate one after the other.


If you don't want to use delay (which is how I'd do this), you could do something like this, using a recursive function.

function animateImage(images, i) {
    $(this).css({
        "opacity" : '0.0',
        "z-index" : "1"
    }).animate({
        opacity: "1.0"
    }, 3000, function() {
        var next = i + 1;
            
        if (next < images.length) {
            animateImage(images, next);
        }
    });
}

animateImage(images, 0);


Use .queue() to set them http://api.jquery.com/queue/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜