简体   繁体   中英

How do you pause before fading an element out using jQuery?

I would like to flash a success message on my page.

I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.

What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.

How can you animate this using jQuery?

jQuery 1.4中的新delay()函数应该可以解决问题。

$('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();

use setTimeout(function(){$elem.hide();}, 5000);

Where $elem is the element you wish to hide, and 5000 is the delay in milliseconds. You can actually use any function within the call to setTimeout() , that code just defines a small anonymous function for simplicity.

While @John Sheehan's approach works, you run into the jQuery fadeIn/fadeOut ClearType glitch in IE7. Personally, I'd opt for @John Millikin's setTimeout() approach, but if you're set on a pure jQuery approach, better to trigger an animation on a non-opacity property, such as a margin.

var left = parseInt($('#element').css('marginLeft'));
$('#element')
    .animate({ marginLeft: left ? left : 0 }, 5000)
    .fadeOut('fast');

You can be a bit cleaner if you know your margin to be a fixed value:

$('#element')
    .animate({ marginLeft: 0 }, 5000)
    .fadeOut('fast');

EDIT : It looks like the jQuery FxQueues plug-in does just what you need:

$('#element').fadeOut({
    speed: 'fast',
    preDelay: 5000
});

For a pure jQuery approach, you can do

$("#element").animate({opacity: 1.0}, 5000).fadeOut();

It's a hack, but it does the job

var $msg = $('#msg-container-id');
$msg.fadeIn(function(){
  setTimeout(function(){
    $msg.fadeOut(function(){
      $msg.remove();
    });
  },5000);
});

根据dansays的评论,以下似乎运作良好:

$('#thing') .animate({dummy:1}, 2000) .animate({ etc ... });

dansays's answer just doesn't work for me. For some reason, remove() runs immediately and the div disappears before any animations happen.

The following works, however (by omitting the remove() method):

$('#foo').fadeIn(500).delay(5000).fadeOut(500);

I don't mind if there are hidden DIVs on the page (there shouldn't be more than a few anyway).

Update for 1.6.2

Nathan Long's answer will cause the element to pop off without obeying delay or fadeOut .

This works:

$('#foo').delay(2000).fadeOut(2000);

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