JS / jQuery:由悬停触发的反向动画?

时间:2017-05-09 10:01:02

标签: javascript jquery html css animation

当我第一次遇到jQuery的.animate函数时,我很激动。但如果我,例如使用.mouseover上的此功能更改框的颜色,它(当然)将完成动画,虽然鼠标已经离开了框,并且在.mouseleave上调用了另一个反转颜色的动画。

这导致例如如果你用鼠标将鼠标悬停在盒子上多次,并且动画重复20次,那么就会拍打。

如果鼠标不在盒子上,可以使用例如停止动画/反转颜色变化。这个问题的功能组合已经被问到:jQuery - Animation transition interrupted by hover

以下是类似动画的此问题的示例代码:http://jsfiddle.net/B9wx8/30/

$('.myClass').animate_and_reverse_animation_if_hover_ends( {...} , 500 );

这似乎不是很优雅和复杂。是否有一些jQuery函数非常类似于.animate,但在例如之后反转动画。盒子里的鼠标不长?

类似的东西:

button.setBackgroundColor(getResources().getColor(R.color.youCustomColor));

2 个答案:

答案 0 :(得分:1)

使用CSS

下面的代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
.bottom, .top {
    width: 200px;
    height: 200px;
}
.bottom { background-color: black; }
.top {
    background-color: red;
    transform: translate(0, 0%);
    transition: transform .3s ease;
    will-change: transform;
}
.top.covered { transform: translate(0, 100%); }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).on('mouseover', '.bottom', function(){
        $(".top").addClass("covered");
    });
    $(document).on('mouseout', '.top', function(){
        $(".top").removeClass("covered");
    });
});
</script>
</head>
<body>
<div id="container">
    <div class="top"></div>
    <div class="bottom"></div>
</div>
</body>
</html>

小提琴:https://jsfiddle.net/beekvang/mpecfc1n/

答案 1 :(得分:0)

所以你更喜欢这样的电话

$('.box1,.box2').animate_and_reverse_animation_if_hover_ends({top: 0}, {top: "-200px"}, 'slow');

哪里没有人(除了你)有什么线索 - 在此之上:

$('.box1,.box2').mouseenter(function () {
    $('.box2').stop().animate({
        top: 0
    }, 'slow');
}).mouseleave(function () {
    $('.box2').stop().animate({
        top: '-200px'
    }, 'slow');
});

第二个版本是恕我直言,优雅,简单,可读,因为它得到...在jQuery世界。

我建议您继续使用它,并使用您在问题中提供的解决方案。但如果你必须,你可以编写自己的jQuery.animate_and_reverse_animation_if_hover_ends()插件,封装第二个剪辑。

更新:

正如CBroe在评论中指出的那样。优雅的真正改进可能是在CSS中进行这种动画/过渡。