2011-02-23 58 views
0

我有这个功能,我想知道为什么的setTimeout不工作:JS的setTimeout和jQuery的功能

$(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中做到这一点?

回答

3

您的超时处理程序中的this值不会成为您认为的值。添加一个明确的变量:

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

你也应该申报“mouseOverTimer”作为一个局部变量处理程序设置代码(即作为“准备”处理的一个局部变量),然后取消超时在“鼠标离开”处理程序:

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); 
    });  

正如我看看这个,我敢肯定的是,“鼠标离开”的代码是不是真的是你想要的东西;具体而言,我认为延迟可能是不必要的。然而,我不是100%确定你想要什么样的东西。

+0

答案就在这里......然而,你可能也想看看本alman的油门/防抖动jQuery插件:http://benalman.com/projects/jquery-油门反弹插件/ – gnarf 2011-02-23 16:27:40

+0

哦,我明白了。谢谢你的答案。无法选择$(self)然后成为一个问题,因为我在使用此函数的单个页面上有多个元素。 – theorise 2011-02-23 16:32:44

+0

没关系,我可以在setTimeout之外设置一个变量,谢谢! – theorise 2011-02-23 16:36:15

0

我也许会这样简化问题:在mouseover我会实例化一个new Date(),getTime()它并将其存储到一个变种。然后在mouseleave上再拍一张日期,再次抓住时间戳。在同样的mouseleave中,做一个评估:如果日期1和日期2之间的差异大于1/2秒,则启动您的操作。否则,您重置日期1.

+0

我在想同样的事情,但即使用户不离开元素,OP也可能想要动画继续。 – Anurag 2011-02-23 16:28:18

+0

伟大的思想家都认为。 :) OP说:“我只想让mouseenter上的动画在鼠标悬停至少半秒之后才能工作”,如果我正确地阅读并且正确地阅读了这些内容,似乎与上述内容一致。 – buley 2011-02-23 16:29:30

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(),这会杀死未决的动画,然后再回到起始位置。如果它从未移动,那么鼠标动画也不会发生(正确 - 它无处可去)。

+0

不错的想法,这本来是理想的,但停止似乎并不奏效。 – theorise 2011-02-23 16:33:48

+0

呵呵,我并不期待那样。如果你不链接两个事件处理程序,它的工作方式是否有所不同? – 2011-02-23 16:37:55

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); 
    });  
});