下面是一个盒子的代码,它有滑动选项(.box-options)在mouseenter上以动画形式从盒子里出来,增加了1000ms的延迟
如果鼠标在完成 1000ms 之前离开该框,我想停止动画(或滑出它的选项)
我不想使用任何外部插件,只有JQuery我有。
$('.box').on('mouseenter', function(){
$(this).find('.box-options').stop().delay(1000).animate({
right: "-42"
},400);
});
您可以执行以下操作,假设您希望在鼠标停止悬停在框上时将动画冻结在其轨道中。
var animInProgress = false;
$('.box').on('mouseenter', function(){
$(this).find('.box-options').animate({
right: "-42"
},400);
animInProgress = true;
setTimeout(stop_animation,1000);
});
$('.box').on('mouseleave', function(){
// if the mouse leaves the box before the animation is finished
if(animInProgress) {
// stop the animation
$(this).find('.box-options').stop()
// or do something else (revert to original pos?)
}
});
function stop_animation() {
animInProgress = false;
}
我会使用CSS动画。它们不仅需要更少的工作来启动和运行,而且浏览器针对CSS进行了疯狂的优化,并且比同等的Javascript补间效果效率高得多。
对于这样的事情,我建议让 on mouseenter 事件将一个类应用于触发 CSS 动画的框选项元素。
$('.box').on('mouseenter', function() {
$(this).find('.box-options').addClass('active');
}).on('mouseleave', function() {
$(this).find('.box-options').removeClass('active');
});
当然,如果你很聪明,你可以将CSS伪选择器:hover
与-webkit-transition
结合使用,无需javascript即可实现这一切。请参阅我的JSFiddle,它完全不使用Javascript。这绝对是管理这种效果的优越方法。