我有这个函数,我想知道为什么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);
});
}); 我尝试在超时时包装鼠标输入事件,但这似乎不是一个好主意。我只想让鼠标键上的动画只在鼠标停留在上面至少半秒钟后才能工作。
或者,有没有更好的jQuery方式呢?
发布于 2011-02-24 00:25:52
超时处理程序中的this值将不是您所认为的值。添加显式变量:
$('.sliding').mouseenter(function() {
var self = this;
mouseOverTimer = setTimeout(function() {
$(self).find('.text').animate({"top": "0"}, 200);
}, 500);
})另外,您应该在处理程序设置代码之外将"mouseOverTimer“声明为局部变量(即,作为"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“代码并不是您真正想要的;具体地说,我认为延迟可能是不必要的。然而,我不是百分之百确定你想要的东西是什么样子的。
发布于 2011-02-24 00:27:06
我可能会这样简化这个问题:在mouseover上,我会实例化一个new Date(),getTime(),并将其存储到一个变量中。然后,在mouseleave上,你可以选择另一个日期,再次抓取时间戳。在相同mouseleave中,执行一个评估:如果日期1和日期2之间的差异大于1/2秒,则触发您的操作。否则,您将重置日期1。
发布于 2011-02-24 00:28:03
您可以尝试这样做,而不是使用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);
});
});这将使鼠标悬停动画延迟500ms。如果您将鼠标移出,它将调用stop(),这将杀死挂起的动画,然后将动画恢复到开始位置。如果它从未移动过,鼠标输出动画也不会发生(正确地-它无处可去)。
https://stackoverflow.com/questions/5093676
复制相似问题