开发者

Fade in images staggered with jQuery

开发者 https://www.devze.com 2023-03-03 07:01 出处:网络
I have a gallery page with many images that I would like to load one by one, or at least give the illusion that each one is fading in one by one.

I have a gallery page with many images that I would like to load one by one, or at least give the illusion that each one is fading in one by one.

I've come up with this:

 $(".fadeInImage").hide();

var counter = 0;
$(".fadeInImage").each(function() {
    counter = counter + 50;
    fade_in(this,counter);

});
function fade_in(obj,counter)
{
    $(obj).bind("load", function () { $(this).delay(counter).fadeIn(); });  
}

This works lovely, and also just loads the images normally if there is no js. But, my question is, as I'm not that expert with jQuery, is there any problems you can foresee? Is th开发者_Python百科ere a better way to do this?

Thanks in advance!


Looks good to me. Although you could simplify it to something like this -- remember to use load event on window due to unpredictable nature of how long it'll take to load images:

$(document).ready(function() {
    $('.fadeInImage').hide();
});

$(window).load(function() {
    $(".fadeInImage").each(function(i) {
       $(this).delay((i + 1) * 50).fadeIn();
    });
});


You can't guarantee that the images will load in the order they appear in the HTML (especially if their sizes differ) so you may not get a smooth fade-...-fade transition. You can use the window's load event to get them to fade in when everything is ready:

$(".fadeInImage").hide();

$(window).load(function () {
    var counter = 0;
    $(".fadeInImage").each(function() {
        counter = counter + 50;

        $(this).delay(counter).fadeIn();
    });
});


I think this way would be more accurate:

var $imgs = $(".fadeInImage").hide();

function fadeOneByOne(i){
   if(i >= $imgs.size()) return;
   $imgs.eq(i).fadeIn(function(){ fadeOneByOne(i+1); })
}

fadeOneByOne(0);
0

精彩评论

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