首页 > 解决方案 > 如何防止CSS动画在每个循环后重置

问题描述

有没有办法在每个循环完成后防止 CSS 动画重置?我希望它从前一个位置而不是初始位置开始。

@keyframes spin{
  0%{
    transform:rotate(0deg);
  }
  50%{
    transform:rotate(180deg);
  }
  100%{
    transform:rotate(180deg);
  }
}

.spinning{
    position: absolute;
    height:50px;
    width:50px;
    top:100px;
    left:100px;
    background-color: lightgrey;
    border-radius: 50%;
    animation: spin 2s linear infinite;
}

.spinning::after{
    content:'';
    position:absolute;
    height:10px;
    width:10px;
    border-radius:50%;
    background-color:red;
    top:-5px;
    left:20px;
}
<!-- begin snippet: js hide: false console: false babel: false -->
<html>
  <head>
    <link rel="" href="">
  </head>
  <body>
    <div class="spinning"></div>
  </body>
</html>

如您所见,每次旋转后,红点都会重置到圆的顶部,但这不是我想要的,我希望它从圆的顶部开始旋转,然后是底部,然后是顶部,然后是底部,然后很快。我英语说得不好,我希望你能明白我想说的。

标签: htmlcsscss-animations

解决方案


点移回原始位置 (0%),因为最后一个keyframe位于180deg。为了使它完成整个循环,您必须在360deg. 所以它仍在重置,但由于360deg0deg在技术上是相同的位置,你不会看到这个“过渡”。

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  75% {
    transform: rotate(360deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.spinning {
  position: absolute;
  height: 50px;
  width: 50px;
  top: 100px;
  left: 100px;
  background-color: lightgrey;
  border-radius: 50%;
  animation: spin 4s linear infinite forwards;
}

.spinning::after {
  content: '';
  position: absolute;
  height: 10px;
  width: 10px;
  border-radius: 50%;
  background-color: red;
  top: -5px;
  left: 20px;
}
<div class="spinning"></div>


推荐阅读