我在基于 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>
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用 from 方法,但也没有运气。任何帮助将非常感激。
创建 DOM之前<script>运行的内容(因为 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>
Run Code Online (Sandbox Code Playgroud)
(注意:我更改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>
Run Code Online (Sandbox Code Playgroud)