2013-04-23 106 views
1

我在菜单上有jquery的悬停效果,它可以正常工作,但如果将鼠标移动到项上的速度提高了几倍,那么动画会继续执行多次,然后进入该区域,对不起如果我不能按照我的意愿解释我的问题,我需要的是某种延迟,所以如果您将鼠标移动很多次,该功能只会触发一次,然后您等待1秒以再次获得效果。谢谢!函数jquery上的延迟

$(".border").hover(function(){ 
    if($(this).next('.sous_menu').is(':visible')){ 
     $('.sous_menu').closest('.border').removeClass('border').addClass('border_active'); 
    }else{ 
     $(this).toggleClass('border_active border', 500); 
    } 
}); 

http://jsfiddle.net/xb8Ss/9/

+1

你可以检查该元素是否是动画:http://stackoverflow.com/questions/724911/how-do-i-find-out-with-jquery-if-an-element-is-being-animated – Adder 2013-04-23 14:30:56

+0

可能应该使用'.stop()'函数在重新激活之前停止动画。 – 2013-04-23 14:31:07

回答

0

尝试添加delay()和切换之前停止()。 stop()将停止任何正在进行的动画,以防止无限动画。而delay()会延迟它放置多少毫秒。

$(this).stop()delay(1000).toggleClass('border_active border', 500); 
+0

太棒了!谢谢大家 !!! – novoa 2013-04-23 15:01:51

0

如果该功能已经被添加检查VAR和chaning它超时执行的最后一秒您可以检查:

// the first time should always be allowed 
var allow = true 

$(".border").hover(function(){ 

    // if 'allow' is false, return without doing anything 
    if(!allow) { 
     return; 
    } 

    // the function is now gonna execute, don't allow 
    // other events from executing the function 
    allow = false; 


    // executing the function 
    if($(this).next('.sous_menu').is(':visible')){ 
     $('.sous_menu').closest('.border').removeClass('border').addClass('border_active'); 
    }else{ 
     $(this).toggleClass('border_active border', 500); 
    } 


    // after a second of the execution of the function, set allow to 
    // true again to allow other events from executing the function 
    setTimeout(function() { 
     allow = true 
    }, 1000) 

}); 
0

如果我正确地理解这个问题,我相信这是什么你正在寻找...

$(document).ready(function() { 
    var canMove = true; 

    $("#moveme").hover(function() { 
     if(canMove) { 
      canMove = false; 

      $(this).css("left", "50px"); 
      setTimeout(function() { canMove = true; }, 1000); 
     } 
    }, function() { 
     $(this).css("left", "10px"); 
    }); 
}); 

的jsfiddle here

上面的悬停代码只会在达到1000(1秒)的“冷却时间”后运行。或者,您可以在悬停出口设置canMove为true,这将确保代码只在每次悬停时运行一次(尽管这应该已经是这种情况)。