Can I use .delay() together with .animate() in jQuery?

≡放荡痞女 提交于 2019-12-03 19:11:33

问题


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

回答1:


I've always managed this kind of things with the help of core setTimeout and clearTimeout js functions.

Here is an example on jsFiddle

Take a look at jquery.hoverIntent plugin too, it gives you a timeout on hover and out events




回答2:


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



回答3:


Looks like there may have been updates to jQuery in this vein since 2011. In Chrome I can use this sans timeout calls:

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



回答4:


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


来源:https://stackoverflow.com/questions/4247772/can-i-use-delay-together-with-animate-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!