简体   繁体   中英

jQuery delay with multiple selectors

I know you can do something like this:

$('#item').fadeOut().delay(1000).fadeIn();

which will fade the element with the id of item out, then wait a second before fading it back in again. But is there a way to fade one item out and a different one back in with a delay inbetween. I've tried this but it didn't work:

$('#item1').fadeOut().delay(1000).('#item2').fadeIn();

Any help much appreciated

Thanks

Use the callback function:

$("#item1").fadeOut( function()
{
  $("#item2")
          // Wait for 600 ms 
          .delay(600)
          // Fade in
          .fadeIn();
});

See the docu: http://api.jquery.com/fadeIn/

fadeIn( [ duration ], [ easing ], [ callback ] )

duration A string or number determining how long the animation will run.

easing A string indicating which easing function to use for the transition.

callback A function to call once the animation is complete.

Fade the second element in within a callback, giving it the delay instead of the first element.

If you want the delay to count just as the first element begins to fade out, subtract the fading speed from the total delay:

// Assuming default fading speed of 400 ms
var speed = 400, delay = 1000;

$('#item1').fadeOut(speed, function() {
    $('#item2').delay(delay - speed).fadeIn(speed);
});

If you want the delay to count after the first element has finished animating, use the full delay value:

$('#item1').fadeOut(speed, function() {
    $('#item2').delay(delay).fadeIn(speed);
});
 setTimeout(function() {  $('#item1').fadeOut();}, 500);
 setTimeout(function() {  $('#item2').fadeIn(); }, 1000);

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