几秒后隐藏div

时间:2009-05-04 17:02:24

标签: javascript jquery timing

我很想知道,在jquery中我怎么能在几秒钟之后隐藏div?比如Gmail的消息。

我已尽力而为,但无法让它发挥作用。

9 个答案:

答案 0 :(得分:231)

这将在1秒(1000毫秒)后隐藏div。

setTimeout(function() {
    $('#mydiv').fadeOut('fast');
}, 1000); // <-- time in milliseconds
#mydiv{
    width: 100px;
    height: 100px;
    background: #000;
    color: #fff;
    text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">myDiv</div>

如果您只想隐藏而不褪色,请使用hide()

答案 1 :(得分:88)

您可以尝试.delay()

$(".formSentMsg").delay(3200).fadeOut(300);

调用div设置延迟时间(以毫秒为单位)并设置要更改的属性,在这种情况下我使用.fadeOut()以便它可以设置动画,但你也可以使用.hide()。

http://api.jquery.com/delay/

答案 2 :(得分:10)

这是一种非常简单的方法。

问题是.delay只会影响动画,所以你需要做的是让.hide()通过给它一个持续时间来表现得像动画。

$("#whatever").delay().hide(1);

通过给它一个很好的短暂持续时间,它看起来就像常规的.hide函数一样。

答案 3 :(得分:9)

jquery offers a variety of methods to hide the div in a timed manner that do not require setting up and later clearing or resetting interval timers or other event handlers. Here are a few examples.

Pure hide, one second delay

// hide in one second
$('#mydiv').delay(1000).hide(0); 

Pure hide, no delay

// hide immediately
$('#mydiv').delay(0).hide(0); 

Animated hide

// start hide in one second, take 1/2 second for animated hide effect
$('#mydiv').delay(1000).hide(500); 

fade out

// start fade out in one second, take 300ms to fade
$('#mydiv').delay(1000).fadeOut(300); 

Additionally, the methods can take a queue name or function as a second parameter (depending on method). Documentation for all the calls above and other related calls can be found here: https://api.jquery.com/category/effects/

答案 4 :(得分:6)

$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
}

来自http://james.padolsey.com/javascript/jquery-delay-plugin/

(允许链接方法)

答案 5 :(得分:3)

使用jQuery计时器还可以让您拥有与附加到对象的计时器相关联的名称。因此,您可以将多个计时器附加到对象上并停止其中任何一个。

$("#myid").oneTime(1000, "mytimer1" function() {
  $("#something").hide();
}).oneTime(2000, "mytimer2" function() {
  $("#somethingelse").show();  
});

$("#myid").stopTime("mytimer2");

eval函数(及其亲属,Function,setTimeout和setInterval)提供对JavaScript编译器的访问。这有时是必要的,但在大多数情况下,它表明存在极其糟糕的编码。 eval函数是JavaScript中最被滥用的特性。

http://www.jslint.com/lint.html

答案 6 :(得分:2)

可能最简单的方法是使用计时器插件。 http://plugins.jquery.com/project/timers然后调用类似

的内容
$(this).oneTime(1000, function() {
    $("#something").hide();
  });

答案 7 :(得分:1)

<script>
      $(function() {
      $(".hide-it").hide(7000);
    });              
</script>

<div id="hide-it">myDiv</div>

答案 8 :(得分:0)

我们可以直接使用

$('#selector').delay(5000).fadeOut('slow');
相关问题