超时的jQuery效果

101

我正在尝试让一个元素淡入,然后在5000毫秒内再次淡出。我知道可以像这样做:

setTimeout(function () { $(".notice").fadeOut(); }, 5000);

但这只是控制淡出,我需要在回调函数中添加上述内容吗?

7个回答

196

更新: 从jQuery 1.4版本开始,您可以使用.delay( n )方法。 http://api.jquery.com/delay/

$('.notice').fadeIn().delay(2000).fadeOut('slow'); 

注意: $.show()$.hide() 默认情况下不会排队,因此如果希望使用 $.delay() 与它们一起使用,则需要进行配置:

$('.notice')
    .show({duration: 0, queue: true})
    .delay(2000)
    .hide({duration: 0, queue: true});

你可以尝试使用队列语法,这可能有效:

jQuery(function($){ 

var e = $('.notice'); 
e.fadeIn(); 
e.queue(function(){ 
  setTimeout(function(){ 
    e.dequeue(); 
  }, 2000 ); 
}); 
e.fadeOut('fast'); 

}); 

或者你可以非常聪明,编写一个 jQuery 函数来完成它。

(function($){ 

  jQuery.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

理论上,(在这里考虑记忆)它将允许您这样做:

$('.notice').fadeIn().idle(2000).fadeOut('slow'); 

1
我想知道为什么你要使用队列,而简单地使用setTimeout也可以。 - SolutionYogi
33
因为如果您使用队列,很容易添加新事件并重复使用代码,而代码重用是一件好事™。 - Kent Fredric
2
请注意,正如jQuery API文档中所述,delay()应该只用于与效果队列相关的事情。如果您需要超时处理其他事情,仍然应该使用setTimeout()。 - scy
哇,感谢@bottlenecked提供的链接。我猜我的示例之所以与jQuery新增功能如此相似,是因为从这个答案到http://bugs.jquery.com/ticket/4102有一个显著的影响链=P - Kent Fredric

23

我刚刚在下面解决了这个问题:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

我会为其他用户保留这篇文章!


14

@strager 的这个技巧很棒。将它实现到 jQuery 中像这样:

jQuery.fn.wait = function (MiliSeconds) {
    $(this).animate({ opacity: '+=0' }, MiliSeconds);
    return this;
}

然后将其用作:

$('.notice').fadeIn().wait(2000).fadeOut('slow');

11
你可以这样做:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

很遗憾,你不能只是执行 .animate({}, 2000) -- 我认为这是一个 bug,并且会报告它。


7

5
为了能够像那样使用它,您需要返回this。如果没有返回,fadeOut('slow')将无法获得要执行该操作的对象。
例如:
  $.fn.idle = function(time)
  {
      var o = $(this);
      o.queue(function()
      {
         setTimeout(function()
         {
            o.dequeue();
         }, time);
      });
      return this;              //****
  }

然后执行以下步骤:
$('.notice').fadeIn().idle(2000).fadeOut('slow');

1

这可以用几行jQuery代码完成:

$(function(){
    // make sure img is hidden - fade in
    $('img').hide().fadeIn(2000);

    // after 5 second timeout - fade out
    setTimeout(function(){$('img').fadeOut(2000);}, 5000);
});​

请查看下面的示例以获取一个可用的范例...

http://jsfiddle.net/eNxuJ/78/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接