如何以最小的影响重新启动CSS动画

Luc*_*ssi 2 css jquery animation

有没有一种方法可以在不克隆元素,不重排DOM,等待(setTimeout / onAnimationEnd)的情况下重新启动CSS动画?

Luc*_*ssi 5

编辑:不需要jQuery或检查。

我基本上只是在下一个绘制的帧处重新启动动画。

此方法不克隆任何元素,不对文档进行重排,设置任何超时或等待动画完成。它是100%灵活的,不需要jQuery。

我没有看到任何类似的东西(甚至在css-tricks上也没有),所以我想与您分享我的想法并听听您的想法。

浏览器支持

document.querySelector('.box').onclick = function(){
  requestAnimation( this );
};

var requestAnimation = function( obj ){
  obj.style.animation = 'none';
  window.requestAnimationFrame(function(){
    obj.style.animation = 'myAnimation 1s';
  });
}
Run Code Online (Sandbox Code Playgroud)
html{ background: #212121; }

.box{
  width: 150px;
  background: white;
  cursor: pointer;
  text-align: center;
  margin: auto;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 3px black;
}
span{
  float: right;
  color: grey;
}
@keyframes myAnimation{
  from{ background: grey; transform: scale(1.2); }
  to{ background: white; transform: scale(1); }
}
Run Code Online (Sandbox Code Playgroud)
<div class="box">I can animate forever!</div>
<span>By Luca Rossi</span>
Run Code Online (Sandbox Code Playgroud)