我能在jQuery中同时使用.delay()和.animate()吗?

19

我有这段代码,用于在我正在工作的网站上滑动打开篮子预览。如果用户悬停在上面,它会保持打开状态,但是我希望在我的悬停回调触发之前有两秒的延迟。这只是为了防止用户不想让鼠标离开篮子区域。

下面是我用来动画显示篮子的代码:

$('.cart_button, .cart_module').hover(function(){
    $(".cart_module").stop().animate({top:'39px'},{duration:500});
}, function(){
    $('.cart_module').stop().animate({top: -cartHeight},{duration:500})
});

以下是我尝试使用的代码,但没有效果:

$('.cart_button, .cart_module').hover(function(){
    $(".cart_module").delay().animate({top:'39px'},{duration:500});
}, function(){
    $('.cart_module').delay().animate({top: -cartHeight},{duration:500})
});

版本1.4.2。什么也没发生,只是没有延迟,我会将我尝试使用的代码添加到我的问题中。 - Sabai
1
可能是重复问题...https://dev59.com/PnNA5IYBdhLWcg3wHp6B - Aaron McIver
4个回答

28
如果你在延迟之前加入stop,它就可以正常工作:
$('.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);
});

7

看起来自2011年以来,jQuery已经有了更新。在Chrome中,我可以使用这个不带超时调用的东西:

$('.thing').hover(function(){
    $(".thing").delay(2000).animate({top:'39px'},{duration:500});
}

$('.thing').delay(2000).animate({top:'39px'}, 500); - Hastig Zusammenstellen

3

我一直都是通过核心的setTimeoutclearTimeout函数来管理这类事情。

这里有一个在jsFiddle上的示例

还可以看看jquery.hoverIntent插件,它可以在鼠标悬停和移出事件上设置超时时间。


3

您需要延迟多长时间?

$('.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 
    });

我忘记设置延迟的时间了,但即使设置了时间也没有任何区别。 - Sabai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接