暂停角度动画

2024-01-03

Angular 2+ 中可以暂停动画吗?我想在鼠标悬停在元素上时暂停动画,并在鼠标移出时从停止的位置恢复动画。

我创建了一个简单的脚本来演示:https://stackblitz.com/edit/scrolling-text https://stackblitz.com/edit/scrolling-text

这是我的组件:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  template: `
    <div class="container">
      <div class="scrolling-text" [@scroll]="state" (@scroll.done)="scrollDone()">Hover to pause!</div>
    </div>
  `,
  styles: [`
    .container {
      height: 30px;
      overflow: hidden;
      position: relative;
      width: 100%;
    }

    .scrolling-text {
      position: absolute;
      white-space: nowrap;
    }

    /* Below doesn't work to pause */

    .scrolling-text:hover, .container:hover {
      -moz-animation-play-state: paused;
      -webkit-animation-play-state: paused;
      animation-play-state: paused;
    }
  `],
  animations: [
    trigger('scroll', [
      state('on', style({left: '-100px'})),
      transition('* => *', [
        style({left: '-100px'}),
        animate(10000, style({left: '100%'}))
      ])
    ])
  ]
})
export class AppComponent  {
  state = 0;

  scrollDone() {
    this.state++;
  }

}

I tried animation-play-state: paused;没有运气:

.scrolling-text:hover, .container:hover {
  -moz-animation-play-state: paused;
  -webkit-animation-play-state: paused;
  animation-play-state: paused;
}

有什么办法让它发挥作用吗?


我找到了一种方法来做到这一点AnimationBuilder.

import { Component, ElementRef, ViewChild } from '@angular/core';
import { style, animate, AnimationBuilder, AnimationPlayer } from '@angular/animations';

@Component({
selector: 'my-app',
template: `
  <div class="container" (mouseover)="player.pause()" (mouseout)="player.play()">
    <div #el class="scrolling-text">Hover to pause!</div>
  </div>
`,
styles: [`
  .container {
    height: 30px;
    overflow: hidden;
    position: relative;
    width: 100%;
  }

  .scrolling-text {
    position: absolute;
    white-space: nowrap;
  }
`]
})
export class AppComponent  {

  @ViewChild('el') el: ElementRef;

  private factory = this.builder.build([
    style({left: '-100px'}),
    animate(10000, style({left: '100%'}))
  ]);
  private player;

  constructor(private builder: AnimationBuilder) { }

  ngOnInit() {
    this.player = this.factory.create(this.el.nativeElement, {});
    this.animate();
  }

  private animate() {
    this.player.reset();

    this.player.onDone(() => {
      this.animate();
    });

    this.player.play();
  }

}

现场演示 https://stackblitz.com/edit/scrolling-text-ja3aju

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

暂停角度动画 的相关文章

随机推荐