Animate elements sequentially using CSS3 and jQuer

2019-07-09 05:30发布

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?

3条回答
萌系小妹纸
2楼-- · 2019-07-09 05:54

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.

查看更多
放我归山
3楼-- · 2019-07-09 06:00

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");
    });
});
查看更多
Rolldiameter
4楼-- · 2019-07-09 06:12

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.

查看更多
登录 后发表回答