gpt4 book ai didi

javascript - JS setTimeout 和 jQuery 函数

转载 作者:行者123 更新时间:2023-11-28 21:25:43 30 4
gpt4 key购买 nike

我有这个函数,但我想知道为什么 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 中是否有更好的方法?

最佳答案

超时处理程序中的 this 值不会是您想象的那样。添加显式变量:

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

此外,您还应该将“mouseOverTimer”声明为处理程序设置代码外部的局部变量(即,作为“就绪”处理程序的局部变量),然后取消“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”代码并不是您真正想要的;具体来说,我认为延迟可能是不必要的。不过,我并不能 100% 确定您想要的东西是什么样子。

关于javascript - JS setTimeout 和 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093676/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com