关于angular:angular中使用TweenMax相关的问题与解决

4次阅读

共计 1158 个字符,预计需要花费 3 分钟才能阅读完成。

2021-3-17 11:27
最近闲来无事,捣鼓捣鼓 CSS
发现了一个比拟好动画库,就是 TweenMax
用起来稍微有点麻烦,然而成果的确能够。

首先在 angular 中应用 TweenMax 就得先通过 npm 装置

1.  npm install --save-dev gsap
2.  npm install --save-dev @types/gsap

而后再引入
import {TweenMax} from "gsap";

就能够在页面中应用了。

遇到的第一个问题就是,想要动画通过按钮触发来不停的播放
然而动画播完一遍当前,怎点按钮都不会触发

前面找到了起因,须要在重复触发的时候,扭转其地位才行,比如说一开始的 X 为 500,动画播完后 X 的地位就是 500 了,再重复触发,地位还是 500 所以不会有作用,所以想要重复触发,就得批改其地位

this.test = new TweenMax('.box',3,{
      x:this.direction?0:500,
      ease:Bounce.easeOut
    })

第二个问题就是,在页面上,想要在动画过程中和完结当前扭转蓝色按钮的状态和文字,后果发现间接用绑定在按钮上的属性不可能实现这个操作

<button [disabled]="isMoveing" style="margin-top: 10px;" nz-button nzType="primary" (click)="repeat()">
    {{describle}}
</button>

this.test = new TweenMax('.box',3,{
      x:this.direction?0:500,
      ease:Bounce.easeOut,
      onStart:function(){
        this.describle = '静止中'
        this.isMoveing = true
      },
      onComplete:function(){
        this.describle = '动'
        this.isMoveing = false
      }
    })

通过一番折腾察觉,其实是 this 指向的问题

上图能够看到,在 TweenMax 办法中,this 指向的是 Tween 这个办法自身,而咱们须要扭转的对象,是处在组件中的,也就是下图所示

定位到了问题所在处,那解决起来就比较简单了,在函数作用域之外的中央定义一个元素指向正确的 this 就行

let _this = this
this.test = new TweenMax('.box',3,{
      x:this.direction?0:500,
      ease:Bounce.easeOut,
      onStart:function(){
        _this.describle = '静止中'
        _this.isMoveing = true
      },
      onComplete:function(){
        _this.describle = '动'
        _this.isMoveing = false
      }
    })

这样就失常了。

正文完
 0