开发者

jQuery Image Fade Sequence?

I have a question regarding jQuery and image fading. I have a bunch of images and I would like to fade each one sequentially to full opacity when you load the page. My html code is be开发者_StackOverflow社区low:

<div class='mod'>
   <img src='image-src' alt='' />
   <div class='mod-text'>
   <h2>Title</h2>
   <p>Caption</p></div>
</div>

<div class='mod'>
   <img src='image-src' alt='' />
   <div class='mod-text'>
   <h2>Title 2</h2>
   <p>Caption 2</p></div>
</div>

Each image has its own corresponding Title and Caption which is displayed one below the other. I would like to have the first image fade in first, then have each following image fade in after. Anybody have an idea? I have a very basic understanding of jQuery. Thanks


You'll need to queue the animations and then start each when the previous ends:

<img src="..." />
<img src="..." />
<img src="..." />
<img src="..." />

var animations = new Array();
// queue all
$("img").each(function() {
    animations.push($(this));
});

// start animating
doAnimation(animations.shift());

function doAnimation(image) {
    image.fadeIn("slow", function() {
        // wait until animation is done and recurse if there are more animations
        if(animations.length > 0) doAnimation(animations.shift());
    });
}


This probably isn't something that you need to implement yourself, check out the jQuery Cycle Plugin.


You can also fade them in sequentially by delaying the effect for each subsequent image like so (note: I'm using window.load to ensure all images are loaded before starting the animations):

$(window).load(function() {

        var delay = 0;

        $('img').each(function() {
            $(this).delay(delay).fadeIn();
            delay += 150;
        });

    });

This is great for overlapping the animations as opposed to waiting til each one completes. It can also be randomized like so:

$(window).load(function() {

        var delay = 0;

        $('img').sort(function() { return (Math.round(Math.random()) - 0.5); }).each(function() {
            $(this).delay(delay).fadeIn(600);
            delay += 150;
        });

    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜