我可以在 jQuery 中将 .delay() 与 .animate() 一起使用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4247772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use .delay() together with .animate() in jQuery?
提问by Henryz
I have this code, which slides open a basket preview on a website I am working on. It stays open if the user is hovered on it, but I want it to have a two second delay before the callback for my hover is triggered. This is just in case the user didn't want the mouse to leave the basket area.
我有这个代码,它在我正在处理的网站上滑动打开一个篮子预览。如果用户悬停在它上面,它会保持打开状态,但我希望它在触发悬停回调之前有两秒钟的延迟。这是以防万一用户不希望鼠标离开篮子区域。
Below is the code I am using to animate the basket:
下面是我用来为篮子设置动画的代码:
$('.cart_button, .cart_module').hover(function(){
$(".cart_module").stop().animate({top:'39px'},{duration:500});
}, function(){
$('.cart_module').stop().animate({top: -cartHeight},{duration:500})
});
Here is the code I tried to use, but had no affect:
这是我尝试使用的代码,但没有影响:
$('.cart_button, .cart_module').hover(function(){
$(".cart_module").delay().animate({top:'39px'},{duration:500});
}, function(){
$('.cart_module').delay().animate({top: -cartHeight},{duration:500})
});
采纳答案by gpasci
I've always managed this kind of things with the help of core setTimeout
and clearTimeout
js functions.
我一直在借助 coresetTimeout
和clearTimeout
js 函数来管理这类事情。
Here is an example on jsFiddle
这是一个关于 jsFiddle的例子
Take a look at jquery.hoverIntent plugintoo, it gives you a timeout on hover and out events
也看看jquery.hoverIntent 插件,它会给你一个悬停和退出事件的超时时间
回答by Chango
If you add the stop before the delay it works just fine:
如果您在延迟之前添加停止它工作得很好:
$('.cart_button, .cart_module').hover(function() {
$('.cart_module').stop(true, true).delay(100).animate({top:'39px'}, 400);
},
function() {
$('.cart_module').stop(true, true).animate({top: -cartHeight}, 250);
});
回答by cbmtrx
Looks like there may have been updates to jQuery in this vein since 2011. In Chrome I can use this sans timeout calls:
看起来自 2011 年以来 jQuery 可能已经在这方面进行了更新。在 Chrome 中,我可以使用这个无超时调用:
$('.thing').hover(function(){
$(".thing").delay(2000).animate({top:'39px'},{duration:500});
}
回答by switz
How long do you want it to delay for????
你想让它延迟多久????
$('.cart_button, .cart_module').hover(function(){
$(".cart_module").delay(2000).animate({top:'39px'},{duration:500}); //two seconds
}, function(){
$('.cart_module').delay(2000).animate({top: -cartHeight},{duration:500}) //two seconds
});