我如何为此JQuery事件添加延迟?

时间:2011-05-29 07:27:27

标签: javascript jquery

这是一个附加一些html的事件:

   $("#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>');
    });

如何在鼠标悬停在所选元素上并附加html之间存在2000毫秒的差距?

2 个答案:

答案 0 :(得分: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 :(得分: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>');
    });
相关问题