GSAP ScrollTrigger 在挂载时触发,而不是在滚动时触发

Posted

技术标签:

【中文标题】GSAP ScrollTrigger 在挂载时触发,而不是在滚动时触发【英文标题】:GSAP ScrollTrigger triggering on mount, not on scroll 【发布时间】:2021-05-24 14:20:27 【问题描述】:

我根据example in this codepen制作了一个带有滚动触发器的动画。

问题是,动画在我加载页面时播放,而不是在我滚动超过预期触发点时播放。

有人知道为什么会这样吗?我在mounted中调用了触发方法,我认为这就是问题所在。但这就是 codepen 示例的方式,并且动画没有在页面加载时触发。在method中调用方法应该只确定页面上有触发器。

我还从 scrollTransition 方法内部的 this.animation() 中删除了调用,因为我认为这可能会调用并触发动画。但是删除括号会使滚动触发标记(我猜是触发器本身)完全从屏幕上消失。

代码如下:

// HelloWorld.vue
<template>
  <div class="empty"></div>
  <div class="hello" ref="hello">
    // content
  </div>
  <div class="empty"></div>
</template>

<script lang="ts">
  import  defineComponent  from 'vue';
  import  gsap, Power3  from 'gsap';
  import  scrollTransition  from '../utils/transitions/scrollTransition';

  export default defineComponent(
    name: 'HelloWorld',
    props: 
      msg: String,
    ,
    methods: 
      animation() 
        gsap.from(this.$refs.hello, 
          autoAlpha: 0,
          duration: 1.2,
          ease: Power3.easeOut,
          y: 400,
        );
      ,
      scroll() 
        scrollTransition(this.$refs.hello, this.animation());
      ,
    ,
    mounted: function () 
      this.scroll();
    ,
  );
</script>


// scrollTransition.ts
import  gsap  from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

export const scrollTransition = (
  trigger: htmlElement,
  animation: gsap.core.Animation,
  props?: Object,
): gsap.plugins.ScrollTriggerInstance =>
  ScrollTrigger.create(
    trigger,
    animation,
    markers: true,
    start: 'top 50%',
    toggleActions: 'play complete none none',
    ...props,
  );

【问题讨论】:

嘿crevulus。如果 ScrollTrigger 的起始位置为负(即在用户必须滚动之前),那么它将立即触发。看起来就是这种情况。这在the most common ScrollTrigger mistakes 中进行了讨论。 【参考方案1】:

它正在触发,因为我没有从我的 animation() 函数返回。

要修复它,你只需要添加一个 return 语句。

animation() 
  return gsap.from(this.$refs.hello, 
    autoAlpha: 0,
    duration: 1.2,
    ease: Power3.easeOut,
    y: 400,
  );
,

【讨论】:

以上是关于GSAP ScrollTrigger 在挂载时触发,而不是在滚动时触发的主要内容,如果未能解决你的问题,请参考以下文章

Vue-Router 和 Gsap ScrollTrigger

Gsap ScrollTrigger :让我的部分在滚动时翻译

Gatsby + GSAP 和 ScrollTrigger 使用 <Link> 的问题

GSAP ScrollTrigger 未按预期工作

GSAP ScrollTrigger - 为每个部分创建时间线

使用 ScrollTrigger 固定水平 GSAP