【问题标题】:Using GSAP with svelte将 GSAP 与 svelte 一起使用
【发布时间】:2020-07-07 17:00:59
【问题描述】:

我在我的基于 CV 的站点的苗条项目中使用 GSAP 时遇到了问题。我对两者都比较陌生。我知道 svelte 有自己的动画库,但我想使用 GSAP 来实现它的时间线功能。作为测试,我尝试更改蓝色方块的颜色,但似乎无法使其正常工作。它要么不会改变,要么根本不存在。我也安装了 GSAP 作为依赖项。这是我的 App.svelte 中的代码:

<script>
    import { gsap } from "gsap";
    gsap.from(".blue", {color: "#8c0", duration: 1});
</script>

<main>
    <div class="blue"></div>
</main>

<style>
  .blue {
        width: 100px;
        height: 100px;
        background-color: blue;
    }
</style>

我也尝试过使用 from 方法,但也没有运气。任何帮助将不胜感激。

【问题讨论】:

  • 在您尝试使用 GSAP 对其进行动画处理之前,您尝试动画化的元素必须位于 DOM 中。试着把脚本标签放在最后。
  • 有关使用 Svelte + GSAP 的更多信息,请参阅 this post

标签: svelte gsap


【解决方案1】:

&lt;script&gt; 的内容 创建 DOM 之前运行(因为 Svelte 通常在代码运行之前不知道它需要创建什么 DOM)。如果你需要对已经创建的 DOM 做一些事情,你必须等到它被挂载,你可以使用 onMount 生命周期函数:

<script>
    import { gsap } from "gsap";
    import { onMount } from "svelte";

    onMount(() => {
        gsap.from(".blue", {color: "#8c0", duration: 1});
    });
</script>

<main>
    <div class="blue"></div>
</main>

<style>
    .blue {
        width: 100px;
        height: 100px;
        color: blue;
        background-color: currentColor;
    }
</style>

(注意:我将background-color 更改为使用currentColor,因为动画color 没有其他效果。)

在 Svelte 中,最好不要使用像 .blue 这样的全局选择器,因为如果你有这个组件的多个实例,GSAP 不会只选择属于这个组件的元素。最好直接传入一个 DOM 元素。您可以使用bind:this 获取对该元素的引用:

<script>
    import { gsap } from "gsap";
    import { onMount } from "svelte";

    let box;

    onMount(() => {
        gsap.from(box, {color: "#8c0", duration: 1});
    });
</script>

<main>
    <div bind:this={box} class="blue"></div>
</main>

<style>
    .blue {
        width: 100px;
        height: 100px;
        color: blue;
        background-color: currentColor;
    }
</style>

Demo here.

【讨论】:

  • 为 Rich 的帮助干杯。我在玩 onMount,所以这很有帮助。继续努力!
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 2020-01-13
  • 2021-12-19
  • 2021-05-23
  • 1970-01-01
相关资源
最近更新 更多