Reverse CSS animation on :hover

自古美人都是妖i 提交于 2019-12-11 04:19:43

问题


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.

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>

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).

This is much closer to the real-world code: https://codepen.io/connexo/pen/eBxMqO

I am also not interested in Javascript-based solutions, only CSS.


回答1:


Instead of using reverse I just created another animation which is the reverse of your current one.

I did it likes this: 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>

Correction: reverse is supported in Safari Desktop: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction


This is my guess on the jumping behaviour using 'reverse' - animation for keyframe a is not played again on hovering.

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%.



来源:https://stackoverflow.com/questions/41225205/reverse-css-animation-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!