2011-05-29 30 views
1

这是追加一些HTML事件:如何为此JQuery事件添加延迟?

$("#feed").live("mouseover", function(){ 
     $("#main").append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>'); 
    }); 

我怎么会导致那里是鼠标移动之间的2000毫秒的间隙所选元素和附加的HTML结束了吗?

回答

7

您将使用超时。

$("#feed") 
    .live("mouseover", function() { 
     $(this).data("timeout", setTimeout(function() { 
      $("#main").append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>');  
     }, 2000)); 
    }); 

在运行代码之前会等待2秒,但如果将鼠标移出元素,它仍会在2秒后显示。所以你要做的是添加一个clearTimeout事件。如果你没有徘徊,这将确保超时不会打勾

$("#feed") 
    .live("mouseout", function() { 
     var timer = $(this).data("timeout"); 
     if (timer) 
      clearTimeout(timer); 
    }); 
+1

+1使用。数据存储计时器手柄 – Alnitak 2011-05-29 08:25:35

+0

@Alnitak,能否请您解释一下,为什么使用。数据存储定时器句柄,是好事吗? – Starx 2011-05-29 09:00:53

+0

@Starx,因为它允许每个元素都拥有自己的定时器,而不必跟踪JS变量的整个负载。 – Alnitak 2011-05-29 11:03:46

2

您还可以使用delay method

此方法的JQuery 1.4
加入用这种方法,你的代码将变为:

$("#feed").live("mouseover", function(){ 
     $("#main").delay(2000).append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>'); 
    });