繁体   English   中英

Angular 在视口中时的 9 个动画

[英]Angular 9 animations when in viewport

我想为我的项目引入动画,特别是<section>和一些标题( h1, h2, h3 )。 我尝试了几种选择; 一种是使用Angular动画,另一种是使用animate.ZC7A62 8CBA22E28EB17B5F5C6AE2A266AZ 。

这两个都按预期工作,但现在我只想<section>当前可见时(第一次)制作动画。

起初我尝试了 https://www.npmjs.com/package/ng2-animate-on-scroll ,但我无法让它工作。 即使使用animate.scss

然后我尝试: https://scrollrevealjs.org/使用https://www.npmjs.com/package/ngx-scrollreveal 这确实有效,但我只能让它使用cubic-bezier(0.25, 0.1, 0.25, 1) 似乎没有其他工作,我想拥有animate.ZC7A62 8CBA22E28EB17B5F5C6AE2A266AZ 或至少fadeInUpfadeInLeftfadeInRight中可用的所有功能

然后我尝试了: https://github.com/Epenance/ngx-animate-in#readme再次,工作并且是迄今为止最好的,因为它使用 angular 动画,但在 IE 中根本不支持,所以是不好。

所以,我的问题是:有没有更好的方法来做到这一点? 理想情况下,我想在将内容滚动到视图时使用 angular 动画,并且我想控制使用哪个 animation。 这可能吗?有没有做过或使用过任何可能有帮助的东西?

最后,使用了一些旧代码,我将它与 ngx-animate 指令合并以得出以下结论:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import {
  AnimationBuilder,
  AnimationFactory,
  AnimationMetadata,
  AnimationPlayer,
  style,
  animate,
} from '@angular/animations';

@Directive({
  selector: '[sxpAnimate]',
})
export class AnimateDirective {
  @Input() animateInAnimation: AnimationMetadata | AnimationMetadata[];
  @HostListener('window:scroll', ['$event']) // for window scroll events
  onScroll() {
    this.animate();
  }

  private animating: boolean;
  private player: AnimationPlayer;
  private defaults: any = {
    offset: 0,
  };

  constructor(
    private el: ElementRef,
    private animationBuilder: AnimationBuilder
  ) {}

  ngOnInit() {
    this.initialize();
    this.animate();
  }

  private initialize(): void {
    let animation: AnimationFactory;

    if (
      this.animateInAnimation !== null &&
      this.animateInAnimation !== undefined
    ) {
      animation = this.animationBuilder.build(this.animateInAnimation);
    } else {
      animation = this.animationBuilder.build([
        style({ opacity: 0, transform: 'translateX(-100px)' }),
        animate(
          '1200ms cubic-bezier(0.35, 0, 0.25, 1)',
          style({ opacity: 1, transform: 'translateX(0)' })
        ),
      ]);
    }

    this.player = animation.create(this.el.nativeElement);
    this.player.init();
  }

  private animate(): void {
    const inView = this.isInViewport();

    if (!inView) this.animating = false;
    if (!inView || this.animating) return;

    this.player.play();
    this.animating = true;
  }

  private isInViewport(): boolean {
    const bounding = this.el.nativeElement.getBoundingClientRect();

    let top =
      bounding.top -
      (window.innerHeight || document.documentElement.clientHeight);
    let bottom = bounding.top + bounding.height + this.defaults.offset;

    return top < 0 && bottom > 0;
  }
}

似乎可以按我的意愿工作; 所以我会以此为基础:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM