为了账号安全,请及时绑定邮箱和手机立即绑定

在视口中时的 Angular 9 动画

在视口中时的 Angular 9 动画

一只名叫tom的猫 2022-12-22 13:04:06
我想为我的项目引入动画,特别是<section>一些标题(h1、h2、h3)。我尝试了几种选择;一种使用Angular动画,另一种使用animate.css。这两个都按预期工作,但现在我只想<section>在 a当前处于视图中时(第一次)设置动画。起初我尝试了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.css或至少fadeInUp、fadeInLeft和fadeInRight中可用的所有功能然后我尝试了:https ://github.com/Epenance/ngx-animate-in#readme再次,有效并且是迄今为止最好的,因为它使用角度动画,但在 IE 中根本不支持,所以这是不好。所以,我的问题是:有更好的方法吗?理想情况下,我希望在将内容滚动到视图中时使用角度动画,并且我希望能够控制要使用的动画。这可能吗?有没有做过或使用过任何可能有帮助的东西?
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

最后,使用了一些我将其与 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;

  }

}

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


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信