Css 来回旋转元素 360

Css rotate element 360 back and forth

正如问题所说,我想将图标以一种方式旋转 360 度,然后以另一种方式重复旋转回来。朝一个方向走很容易,我不明白的是停下来然后朝另一个方向走。

#loading {
    -webkit-animation: rotation 2s infinite linear;
}

@-webkit-keyframes rotation {
from {
    -webkit-transform: rotate(0deg);
    }
to {
    -webkit-transform: rotate(359deg);
}
}

<i id="loading" class="material-icons">autorenew</i>

我已经尝试创建另一个方向的旋转,但它似乎不适用。

@-webkit-keyframes rotationBackwards {
from {
    -webkit-transform: rotate(359deg);
    }
to {
    -webkit-transform: rotate(0deg);
}
}

转换不适用于内联元素。您必须让您的元素成为块级元素(请参阅规范中的 Transformable Elements - 如果您包含武术图标,这将默认设置)。

动画本身可以简单地完成,前半部分 (50%) 旋转到 360 度,后半部分旋转回 0 度。请注意,动画的持续时间分为两个方向(给定 2s 动画,每个方向将花费 1s)。

#loading {
  display: inline-block;
  animation: rotation 2s infinite linear;
}

@keyframes rotation {
  50% {
    transform: rotate(360deg);
  }
  100% {
    transform: rotate(0deg);
  }
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<i id="loading" class="material-icons">autorenew</i>

这是另一个想法,只需使用 animation-directionalternate 值并保持初始动画:

#loading {
  animation: rotation 2s infinite linear alternate;
}

@keyframes rotation {
  /*from {
    transform: rotate(0deg); no needed to define this
  }*/
  to {
    transform: rotate(360deg);
  }
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<i id="loading" class="material-icons">autorenew</i>