简体   繁体   中英

Animate elements sequentially using CSS3 and jQuery

I'm a beginner to jQuery (and CSS3 and everything else for that matter) and am wondering how to automatically animate three different elements (images, in this case) so that they appear one after the other in a sequence - #1, #2, #3 - when the page loads. Here's my CSS:

img#element3 {
    position:absolute;
    opacity:0;
    top:25px;
}

img#element2 {
    position:absolute;
    opacity:0;
    top:270px;
    left:60px;
    margin:10px 0;
}

img#element1 {
    position:absolute;
    opacity:0;
    top:328px;
    left:70px;
    margin:10px 0;
}

For the jQuery, I tried to modify the solution in this post but it's not working. Here's what I did for jQuery:

$(document).ready(handler)
    $("#element3").animate({opacity: "1"}, "slow", function() {
    $("#element2").animate({opacity: "1"}, "slow", function() {
    $("element1").animate({opacity: "1"}, "slow", function() {
    });
});
});

Is there a way to do this using just CSS3 animations or transitions? If not, what's the proper way to do so using jQuery, and how do you specify orders and delays to do so?

You could not do the staged animation with CSS alone.

Your code has a lot of syntax problems. You can consult your error console or use a tool such as JSLint .

I'd probably use...

$(document).ready(function() {
    $("#element3").fadeIn('slow', function() {
        $("#element2").fadeIn('slow', function() {
            $("#element1").fadeIn('slow');
        });
    });
});

jsFiddle .

A little cleaner if you use a class, or a multiple selector with .each() :

$(document).ready(function() {
    $("#element3,#element2,#element1").each(function(i) {
        $(this).delay(600*i).animate({opacity: "1"}, "slow");
    });
});

...or if the order is reversed:

$(document).ready(function() {
    $( $("#element3,#element2,#element1").get().reverse() ).each(function(i) {
        $(this).delay(600*i).animate({opacity: "1"}, "slow");
    });
});

This is perfectly possible with css3 animations, unlike the marked answers says.

To build on his solutions:

use keyframes and animation-delay to fire animations one after the other.

@keyframes 'fadein' {
    from { opacity: 0; }
    to { opacity: 1; }
}

just increase the animation-delay on each element to be the equal to the sum of the previous elements animation-duration values.

and of course make sure to use modernizr with a js fallback!

here's the complete solution for webkit; apply other browser prefixes as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM