过渡到动画之外?

Gag*_*Boy 5 javascript css jquery animation

所以我有一个盒子.box。这样可以无限地重复旋转动画。

@keyframes spin {
  0% {transform:rotate(0deg);}
  100% {transform:rotate(360deg);}
}
Run Code Online (Sandbox Code Playgroud)

仅当框的第二个类名称正在运行时才应用动画

.box.running {
  animation-name:spin;
Run Code Online (Sandbox Code Playgroud)

这样做的目的是使我可以轻松地通过javascript停止动画。(通过删除第二个类名。)

我希望它可以从动画中的任意位置平稳过渡到现在的正常旋转0deg

任何帮助将非常感激。

Iva*_*van 2

我设法使用 CSS 让它工作。JS 允许我们切换类名,仅此而已。您必须为动画使用两个类:一个类将使 div 旋转 ( .spin),另一个类将终止旋转 ( .end)。两者使用相同的@keyframes、具有相同的速度并且是线性的。

  • .spin持续时间无限长
  • .end持续时间为0.5秒

基本上,当 JS 脚本(按下按钮时)该类.end被添加到 div 中,因此.spin's 属性animation被 ' 覆盖.ends,允许它将 div 旋转回其原始位置。

var a = function() {

  document.querySelector('.box').setAttribute('class', 'box spin end')

}

document.querySelector('#end').onclick = function() {
  a()
}
Run Code Online (Sandbox Code Playgroud)
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.box {
  width: 100px;
  height: 100px;
  background-color: purple;
  animation-fill-mode: backwards;
}

.spin {
  animation: spin 2s infinite linear;
}

.end {
  animation: spin 2s 0.5s linear;
}
Run Code Online (Sandbox Code Playgroud)
<div class="box spin"></div>

<br>

<button id="end">STOP SPIN</button>
Run Code Online (Sandbox Code Playgroud)

另外不要忘记将属性设置animation-fill-mode.boxbackwards