CSS animation on hover stay at last keyframe when

2019-01-26 20:09发布

问题:

I am trying to get this animation to stay in its last keyframe on hover but it keeps reverting back to the beginning. I don't mind if I hover off it reverts but not during the hover. I looked through a lot of stack questions and everyone said to uses the animation-fill-mode: forwards, but that doesn't seem to work.

Here is my code and a link to a jsfiddle

.circle:hover .spin {
  -webkit-animation-name: drop;
  -webkit-animation-duration: 1s;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-direction: alternate;
  -webkit-animation-timing-function: ease-out;
  -webkit-animation-delay: 0;
  -webkit-animation-fill-mode: forwards;
}
@-webkit-keyframes drop {
  100% {
    -webkit-transform: rotate(90deg);
  }
}

回答1:

For those of you with a similar problem, first make sure you are using animation-fill-mode: forwards. See this related question.

In this specific case, the following is relevant:

CSS Transforms Module Level 1

A transformable element is an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption.

Since the .circle element is a span, it is inline by default, therefore the property transform: rotate() won't have an effect on it after the animation ends. Changing the display of it to either inline-block or block will solve the problem.

You should also be using the animation shorthand. In addition, add in other vendor prefixes:

Updated Example Here

.circle:hover .spin {
    display:inline-block;
    -webkit-animation: drop 1s 1 alternate ease-out forwards;
    -moz-animation: drop 1s 1 alternate ease-out forwards;
    animation: drop 1s 1 alternate ease-out forwards;
}