如何在 Angular 2 中执行无限动画?

2024-05-19

基本上,我想利用 Angular 中的 web-animations-api polyfill(当前为 4)来对元素执行无限动画。

让我们看一个基本的非角度示例:

var ball = document.getElementById('ball');

ball.animate([
  { transform: 'scale(0.5)' },
  { transform: 'scale(1)' }
], {
  duration: 1000,
  iterations: Infinity,
  direction: 'alternate',
  easing: 'ease-in-out'
});
.container {
  position: relative;
  width: 100%;
  height: 200px;
}

.ball {
  position: absolute;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px solid #E57373;
  background: #F06292;
  box-shadow: 0px 0px 15px #F06292;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.2.5/web-animations.min.js"></script>
<div class="container">
  <div class="ball" id="ball"><div>
</div>

我如何将其翻译成 Angular?

这是我到目前为止所尝试过的,但只有效一次:

animations: [
  trigger('scale', [
    transition('* <=> *', animate('1s ease-in-out', keyframes([
      style({ transform: 'scale(0.5)' }),
      style({ transform: 'scale(1)' })
    ]))) // How do I specify the iterations, or the direction? 
  ])
]

有没有办法使用 @angular/animation 插件来做到这一点,而不是存储 ElementRef 并按照上面的示例进行操作?或者也许我误解了这个插件的用途?

提前致谢。


我正在为我的项目寻找无限动画。中没有这方面的文档angular.io。所以我尝试了这种方法,花了我很多时间来实现这一目标。希望它能帮助其他人。 首先定义animation在你的class.

animations: [
trigger('move', [
  state('in', style({transform: 'translateX(0)'})),
  state('out', style({transform: 'translateX(100%)'})),
  transition('in => out', animate('5s linear')),
  transition('out => in', animate('5s linear'))
]),
]

然后将其插入你的html

<div [@move]="state" (@move.done)="onEnd($event)"></div>

然后设置state = 'in' and in ngAfterViewInit()生命周期挂钩,更新您的state适当的价值'out' with setTimeout函数和结束回调函数后,更新你的state财产价值转化为'in'并检查你的state财产价值,如果in然后更新为out by setTimeout像这样的功能

export class AppComponent implements AfterViewInit {
  state = 'in';
  ngAfterViewInit() {
    setTimeout(() => {
      this.state = 'out';
    }, 0);
  }
  onEnd(event) {
    this.state = 'in';
    if (event.toState === 'in') {
      setTimeout(() => {
        this.state = 'out';
      }, 0);
    }
  }
}

快乐编码:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Angular 2 中执行无限动画? 的相关文章

随机推荐