JS setTimeout& jQuery函数

时间:2011-02-23 16:23:20

标签: javascript jquery settimeout

我有这个功能,我想知道为什么setTimeout不起作用:

$(document).ready(function() {      
    $('.sliding .text').css("top","130px")     

    $('.sliding').mouseenter(function() {       
        mouseOverTimer = setTimeout(function() {
            $(this).find('.text').animate({"top": "0"}, 200);             
        }, 500);       
    })
    .mouseleave(function() { 
        $(this).find('.text').delay(500).animate({"top": "130px"}, 400); 
    });       
});     

我尝试在暂停时包装mouseenter事件,但这似乎不是一个好主意。我只想让mouseenter上的动画仅在鼠标经过它至少半秒后才能工作。

或者,有没有更好的方法在jQuery中执行它?

4 个答案:

答案 0 :(得分:3)

超时处理程序中的this值将不是您认为的那样。添加一个显式变量:

   $('.sliding').mouseenter(function() {   
        var self = this;    
        mouseOverTimer = setTimeout(function() {
            $(self).find('.text').animate({"top": "0"}, 200);             
        }, 500);       
    })

此外,你应该将“mouseOverTimer”声明为局部变量 outside 处理程序设置代码(即作为“ready”处理程序的局部变量),然后取消“mouseleave”中的超时“处理程序:

    var mouseOverTimer = null;

   $('.sliding').mouseenter(function() {   
        var self = this;    
        mouseOverTimer = setTimeout(function() {
            $(self).find('.text').animate({"top": "0"}, 200);             
        }, 500);       
    })
   .mouseleave(function() { 
        $(this).find('.text').delay(500).animate({"top": "130px"}, 400); 
        cancelTimeout(mouseOverTimer);
    });       

当我看到这个时,我很确定“mouseleave”代码并不是你想要的;具体来说,我认为延迟可能是不必要的。然而,我不是百分之百确定你想要的东西。

答案 1 :(得分:0)

我或许可以通过这种方式简化问题:在mouseover上,我会在其上实例化new Date()getTime()并将其存入var。然后在mouseleave上你再拿一个日期,再次抓住时间戳。在同一个mouseleave中,进行评估:如果日期1和日期2之间的差异大于1/2秒,则会触发您的操作。否则,您重置日期1。

答案 2 :(得分:0)

你可以试试这个,而不是使用setTimeout:

$(document).ready(function() {      
    $('.sliding .text').css("top","130px")     

    $('.sliding').mouseenter(function() {       
        $(this).find('.text').stop().delay(500).animate({"top": "0"}, 200);             
    })
    .mouseleave(function() { 
        $(this).find('.text').stop().animate({"top": "130px"}, 400); 
    });       
});

这会将鼠标悬停动画延迟500毫秒。如果你鼠标移出,它会调用stop(),这会杀死待处理的动画,然后动画回到起始位置。如果它从未移动过,那么鼠标移动动画也不会发生(正确 - 它无处可去)。

答案 3 :(得分:0)

另一种方法

mouseIn = false;
$(document).ready(function() {      
    $('.sliding .text').css("top","130px")     

    $('.sliding').mouseenter(function() {   
        mouseIn = true;  
        mouseOverTimer = setTimeout(function() {
            if(mouseIn==true)
                 $(this).find('.text').animate({"top": "0"}, 200);             
        }, 500);       
    })
    .mouseleave(function() {
        mouseIn=false;
        $(this).find('.text').delay(500).animate({"top": "130px"}, 400); 
    });       
});