CSS关键帧动画优雅完成

Posted

技术标签:

【中文标题】CSS关键帧动画优雅完成【英文标题】:CSS keyframes animation gracefully finished 【发布时间】:2020-08-25 03:41:41 【问题描述】:

我有一个正在旋转的图标动画。

它可能会在任何意想不到的时间结束。

所以我的问题是。有没有什么办法在停止旋转之前使用纯 CSS 完成它到结束关键帧?

我现在有这个代码:

我确实尝试过过渡,但没有任何好的结果:


.loop 
  transition: 400ms;
  transform: rotate(180deg);

  &:hover 
    animation: rotation 400ms infinite linear;
  


@keyframes rotation 
  from 
    transform: rotate(180deg);
  
  to 
    transform: rotate(0deg);
  

【问题讨论】:

请不要添加代码图像,它没用而且占用很多空间并且您已经添加了代码 【参考方案1】:

我写了这个指令,它按我的预期工作。

import  Directive, ElementRef, Input  from '@angular/core';

@Directive(
  selector: '[appRotate]'
)
export class RotateDirective 
  speedQueue: Array<number>= [];

  _speed = 0;
  @Input('appRotate') set speed(value: number = 0) 
    const steps = 5;
    const step = (value - this._speed) / steps;
    this.speedQueue = new Array(steps).fill(0).map((_, i) => (i+1) * step + this._speed);
  

  constructor(private el: ElementRef) 
    let rot = 0;
    const loop = () => 
      if (this.speedQueue.length) 
        this._speed = this.speedQueue.shift();
      
      rot += this._speed * 360;
      this.el.nativeElement.style.transform = `rotate($rot % 360deg) scaleX(-1)`;
      requestAnimationFrame(loop);
    ;
    requestAnimationFrame(loop);
  


<span class="material-icons loop" [appRotate]="speed">
  loop
</span>

<div>
  <input type="radio" name="speed" (click)="speed=0">0
  <input type="radio" name="speed" (click)="speed=0.02">2%
  <input type="radio" name="speed" (click)="speed=0.08">8%
</div>

它是这样工作的:

这不是 CSS 解决方案。

【讨论】:

以上是关于CSS关键帧动画优雅完成的主要内容,如果未能解决你的问题,请参考以下文章

CSS关键帧动画中的平滑旋转

CSS3滤镜模糊关键帧动画

CSS3 关键帧动画:结束并停留在最后一帧

您可以使用 JavaScript 将 CSS 关键帧动画“强制”到其最终状态吗?

关键帧动画问题

CSS 模块和 CSS 关键帧动画