GSAP 获取不到 元素问题

610 阅读1分钟

页面报错如下: GSAP target .class not found

结论:获取时机不对

我当时的代码是这么写的

<template>
    <div class="box red"></div>
</template>

<script setup>
import { gsap } from "gsap";

const t1 = gsap.timeline()

t1.to(".red", { x: 100, duration: 1 }, 1)
</script>

<style scoped>
.box {
    height: 100px;
    width: 100px;
}

.red {
    background-color: red;
}
</style>

看到报错时,我一脸疑惑,为什么他会获取不到元素呢? 于是我先后先查了class类名是否写错,使用ref获取,以及使用document获取,都无法解决问题,甚至一度怀疑是不是我引入有问题

于是我又回头看了看我的代码,陷入了沉思,我灵光一闪,获取的时机不对,在gsap执行时相关Dom还没有渲染出来,自然获取不到

于是我更改代码如下:

<template>
    <div class="box red"></div>
</template>

<script setup>
import { gsap } from "gsap";
import { onMounted } from "vue";

onMounted(() => {
    const t1 = gsap.timeline()

    t1.to(".red", { x: 100, duration: 1 }, 1)
})

</script>

<style scoped>
.box {
    height: 100px;
    width: 100px;
}

.red {
    background-color: red;
}
</style>