简体   繁体   中英

jQuery Animation, Chaining, .each() and .animate() (or fadeIn() and fadeOut())

I'm having a bit of a trouble trying to figure this out today, i want to make 5 items inside my DOM (which is listed under the same attribute element, $('.elements')) fade in and out, and after reading up a bit on the API i thought.each() would be a fabulous idea to implement a fade in and fade out showcase gallery.

However, i'm currently using:

$('.elements').each(function() {
    $(this).fadeIn(2000).delay(200).fadeOut(2000).show();
})

but everything gets faded in and out at once.

How do i do a sequential effect where everything is chained together and it starts from the first item in the list (aka - $('elements').eq(0)?) down to the last one, and then restarts again?

Do i really need a while loop to do this in javascript/jquery? I was hoping there would be a similar function that i could chain for jQuery to perform to reduce load and filesize.

Also, is there a way to restrict the images from overflowing out from my div?

(function loop() {
  $('.elements').each(function() {
    var $self = $(this);
    $self.parent().queue(function (n) {
      $self.fadeIn(2000).delay(200).fadeOut(2000, n);
    });
  }).parent().promise().done(loop);
}());

demo: http://jsfiddle.net/uWGVN/2/

updated to have it looping without end.


2nd update : a different, probably more readable, approach:

(function fade(idx) {
  var $elements = $('.elements');
  $elements.eq(idx).fadeIn(2000).delay(200).fadeOut(2000, function () {
    fade(idx + 1 < $elements.length ? idx + 1 : 0);
  });
}(0));

demo: http://jsfiddle.net/uWGVN/3/

You can add a callback

offical doc:

('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

and call the same function with i++ et $('.elements').eq(i)

http://jsfiddle.net/dFnNL/

For your overflowing, style it with CSS:

div.(class) { position:relative; overflow:hidden; }

Beautiful way:

(function hideNext(jq){
        jq.eq(0).hide("slow", function(){
            (jq=jq.slice(1)).length && hideNext(jq);
        });

})($('a'))

last first:

(function hideNext(jq){
                jq.eq(jq.length-1).hide("slow", function(){
                    (jq=jq.slice(0,length-1)).length && hideNext(jq);
                });

})($('a'))

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