将 GSAP 与 svelte 结合使用
Using GSAP with svelte
我在基于 CV 的站点的 svelte 项目中使用 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 方法,但也没有成功。非常感谢任何帮助。
<script>
运行 在 创建 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 中,最好不要使用全局 select 或 .blue
之类的,因为如果您有此组件的多个实例,GSAP 将不只是 select 属于的元素这个组件。最好直接传入一个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>
我在基于 CV 的站点的 svelte 项目中使用 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 方法,但也没有成功。非常感谢任何帮助。
<script>
运行 在 创建 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 中,最好不要使用全局 select 或 .blue
之类的,因为如果您有此组件的多个实例,GSAP 将不只是 select 属于的元素这个组件。最好直接传入一个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>