我正在尝试让一个元素淡入,然后在5000毫秒内再次淡出。我知道可以像这样做:
setTimeout(function () { $(".notice").fadeOut(); }, 5000);
但这只是控制淡出,我需要在回调函数中添加上述内容吗?
更新: 从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');
我刚刚在下面解决了这个问题:
$(".notice")
.fadeIn( function()
{
setTimeout( function()
{
$(".notice").fadeOut("fast");
}, 2000);
});
我会为其他用户保留这篇文章!
@strager 的这个技巧很棒。将它实现到 jQuery 中像这样:
jQuery.fn.wait = function (MiliSeconds) {
$(this).animate({ opacity: '+=0' }, MiliSeconds);
return this;
}
然后将其用作:
$('.notice').fadeIn().wait(2000).fadeOut('slow');
$('.notice')
.fadeIn()
.animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms
.fadeOut('fast');
很遗憾,你不能只是执行 .animate({}, 2000) -- 我认为这是一个 bug,并且会报告它。
Ben Alman编写了一个名为doTimeout的优秀的jQuery插件,它具有许多不错的功能!
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');
这可以用几行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);
});