2012-12-20 15 views
0

我有这样的代码:为什么jQuery mouseenter /离开动画两次?

$(document).ready(function(){ 
    $('.first').mouseenter(function(){ 
     $(this).animate({ 
      top: '115px' 
     }, 500); 
    }); 
    $('.first').mouseleave(function(){ 
     $(this).animate({ 
     top: '127px' 
     }, 500); 
    }); 
}); 

当我运行我的。首先DIV上升和下降至少两次,如果不是更多,我不知道这可能是为什么。

感谢

+1

当你改变顶部时,div移动得足够远吗? e鼠标离开div区域? –

+0

你需要向我们展示dom :) –

+3

你应该在这个实例中停止()这个动画队列,然后再添加一个新的动画。 '$(this).stop()。animate(...' – Shmiddty

回答

3

您需要添加更多的动画之前停止动画队列中,如果你不想让他们建立:http://jsfiddle.net/bgjxk/

$(document).ready(function(){ 
    $('.first').mouseenter(function(){ 
     $(this).stop().animate({ 
      top: '115px' 
     }, 500); 
    }); 
    $('.first').mouseleave(function(){ 
     $(this).stop().animate({ 
     top: '127px' 
     }, 500); 
    }); 
});​ 

你也可以使用CSS3过渡来完成同样的事情,更顺利,不用担心动画队列:http://jsfiddle.net/bgjxk/1/

.first{ 
    ... 
    position:absolute; 
    top:127px; 
    transition:top .25s linear; /* use them vendor prefixes */ 
} 
.first:hover{ 
    top:115px; 
}