在:hover上反转CSS动画 [英] Reverse CSS animation on :hover
问题描述
我试图在悬停元素时使动画反向播放。它不起作用,我不明白为什么以及如何使其起作用。 动画仅跳回关键帧0%,没有任何动画。
I am trying to make an animation play reverse when hovering an element. It does not work, I don't understand why and how to get it to work. The "animation" just jumps back to keyframe 0% without any animation.
该代码段仅在Chrome和Safari中有效。
The snippet works only as intended in Chrome and Safari.
http://codepen.io/anon/pen/YpBaZq
div {
-webkit-animation-fill-mode: forwards;
animation-duration: 2s;
animation-name: a;
background-color: #a00;
display: inline-block;
padding: 50px;
}
div:hover {
-webkit-animation-fill-mode: backwards;
animation-duration: 2s;
animation-name: a;
animation-direction: reverse;
}
@keyframes a {
0% {
padding: 50px;
}
100% {
padding: 100px 200px;
}
}
<div></div>
这只是一个极其简化的示例,因此请不要提出非动画方法(可能是动画与:hover
上的过渡相结合,我尝试过也无法使用)
This is just an extremely simplified example, so please don't suggest non-animation methods (except maybe an animation combined with a transition on :hover
which I tried and couldn't get to work either).
这更接近于实际代码: https:// codepen。 io / connexo / pen / eBxMqO
This is much closer to the real-world code: https://codepen.io/connexo/pen/eBxMqO
我对基于Javascript的解决方案也不感兴趣,只有CSS。
I am also not interested in Javascript-based solutions, only CSS.
推荐答案
我没有创建 reverse
,而是创建了另一个动画,该动画与您当前的动画相反。
Instead of using reverse
I just created another animation which is the reverse of your current one.
我确实喜欢这样: http://codepen.io / anon / pen / zoeWLO
div {
-webkit-animation-fill-mode: forwards;
animation-duration: 2s;
animation-name: a;
background-color: #a00;
display: inline-block;
padding: 50px;
}
div:hover {
-webkit-animation-fill-mode: forwards;
animation-duration: 2s;
animation-name: ra;
}
@keyframes a {
0% {
padding: 50px;
}
100% {
padding: 100px 200px;
}
}
@keyframes ra{
0% {
padding: 100px 200px;
}
100% {
padding: 50px;
}
}
<div></div>
更正:
< Safari桌面支持code> reverse : https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction
这是我对使用反向的跳跃行为的猜测-悬停时不会再播放关键帧 a
的动画。
This is my guess on the jumping behaviour using 'reverse' - animation for keyframe a
is not played again on hovering.
关键帧 a
的动画在2秒后达到100%。现在,您将鼠标移入。通过 reverse
的效果, a
的100%现在为0%,这使得它变得更小。但是由于关键帧 a
已经完成播放,因此div只会跳到0%,而不是过渡到100%。
The animation of keyframe a
is at 100% after 2 seconds. Now you move your mouse in. With the effect of reverse
, a
at 100% is now 0%, which makes it become smaller. But since keyframe a
is already done playing, the div would just jump to 0% instead of transitioning to 100%.
这篇关于在:hover上反转CSS动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!