2015-08-21 89 views
1

我使用.mouseenter()和.mouseleave()做一个动画到我的按钮。问题是,当我多次移动我的光标在按钮,它不断重复.mouseenter()我希望它完成动画,一旦光标保持悬停在其上面,直到动画时间完成,并且如果它在动画完成之前离开按钮,动画应该停止。对于.mouseleave()如果在动画完成之前将光标悬停在其上,则应停止动画。 问题与.mouseleave()和.mouseenter()

 
 
    $(document).ready(function(){ 
 
    $('#button').mouseenter(function(){ 
 
     $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
 
    }); 
 
    $('#button').mouseleave(function(){ 
 
     $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
 
    }); 
 
    });
#button{ 
 
    width:100px; 
 
    height:50px; 
 
    background-color:red; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
 
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script> 
 
<div id="button"></div>

+0

你提到它不断重复动画。你想要它做什么? – jasonwarford

+0

是否有一个原因,你这样做与jQuery的?你可以用CSS实现同样的效果。 – cocoa

+2

这就是这些事件应该如何工作。如果您想停止动画,请参阅http://stackoverflow.com/questions/18211280/how-to-stop-an-animation-queue-in-jquery – Teemu

回答

2

您可以使用标志进入和离开。然后检查相应的标志,并完成当前动画当进入/离开事件发生,这样的事情:

$(document).ready(function() { 
    var isEntering = false, // Create flags 
     isLeaving = false; 
    $('#button').mouseenter(function() { 
     isEntering = true; // Set enter flag 
     if (isLeaving) { // Check, if leaving is on process 
      $(this).finish(); // If leaving, finish it 
      isLeaving = false; // Reset leaving flag 
     } 
     $(this).animate({ 
      backgroundColor: '#ffce00', 
      width: '+=1em' 
     }, 100); 
    }); 
    $('#button').mouseleave(function() { 
     isLeaving = true; // Set leave flag 
     if (isEntering) { // Check if entering is on process 
      $(this).finish(); // If it is, finish it 
      isEntering = false; // Reset enter flag 
     } 
     $(this).animate({ 
      backgroundColor: '#1e7989', 
      width: '-=1em' 
     }, 100); 
    }); 
}); 

A live demo at jsFiddle

0

如果你只希望它运行一次,你可以在事件触发后解除绑定:

$(document).ready(function(){ 
    $('#button').mouseenter(function(){ 
     $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
     $(this).unbind('mouseenter'); 
    }); 
    $('#button').mouseleave(function(){ 
     $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
     $(this).unbind('mouseleave'); 
    }); 
    }); 
+1

这不是'.one()'的用途吗? – Barmar

+0

但我不认为你理解这个问题。他不希望它只发生一次,他只是不希望它们重叠。 – Barmar

1

尝试增加.stop(),它将从排队停止动画。

$(document).ready(function(){ 
    $('#button').mouseenter(function(){ 
     $(this).stop().animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
    }); 
    $('#button').mouseleave(function(){ 
     $(this).stop().animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
    }); 
}); 

问候, Gados

+0

当我在div上多次移动光标时,它会缩小直到它消失。 –