vue 实现文字动画
使用 CSS 过渡和动画实现文字动画
在 Vue 中,可以利用 CSS 的 transition 或 @keyframes 实现文字动画效果。通过绑定动态类名或样式,控制动画的触发条件。
<template>
<div>
<div :class="{ 'fade-in': show }">这是一段渐显文字</div>
<button @click="show = !show">切换动画</button>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.fade-in {
opacity: 0;
transition: opacity 1s ease-in;
}
.fade-in.active {
opacity: 1;
}
</style>
使用 Vue 的 <transition> 组件
Vue 内置的 <transition> 组件可以更方便地实现进入/离开动画,支持 CSS 和 JavaScript 钩子。

<template>
<div>
<button @click="show = !show">切换文字</button>
<transition name="fade">
<p v-if="show">这段文字会淡入淡出</p>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用第三方动画库(如 Animate.css)
结合 Animate.css 可以快速实现丰富的预设动画效果,通过直接添加类名即可。
<template>
<div>
<button @click="animate = !animate">触发动画</button>
<div class="animated" :class="{ 'bounce': animate }">弹跳文字效果</div>
</div>
</template>
<script>
export default {
data() {
return {
animate: false
}
}
}
</script>
<style>
@import 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css';
</style>
使用 GSAP 实现高级动画
对于复杂的序列动画或精细控制,GSAP 库提供了强大的时间轴功能。

<template>
<div ref="textElement">这段文字会动态缩放和变色</div>
<button @click="playAnimation">播放动画</button>
</template>
<script>
import { gsap } from 'gsap'
export default {
methods: {
playAnimation() {
gsap.to(this.$refs.textElement, {
duration: 1,
scale: 1.5,
color: '#ff0000',
yoyo: true,
repeat: 1
})
}
}
}
</script>
逐字显示动画(打字机效果)
通过 JavaScript 控制字符逐个显示,模拟打字效果。
<template>
<div>{{ displayedText }}</div>
</template>
<script>
export default {
data() {
return {
fullText: '这是逐字显示的打字机效果',
displayedText: '',
currentIndex: 0
}
},
mounted() {
this.typeWriter()
},
methods: {
typeWriter() {
if (this.currentIndex < this.fullText.length) {
this.displayedText += this.fullText.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.typeWriter, 100)
}
}
}
}
</script>
文字路径动画
使用 SVG 和 <textPath> 元素可以让文字沿着路径运动。
<template>
<svg viewBox="0 0 200 100">
<path id="textPath" d="M10,50 Q100,10 190,50" fill="none" />
<text>
<textPath href="#textPath">沿曲线运动的文字</textPath>
</text>
</svg>
</template>
<style>
text {
font-size: 8px;
fill: #333;
}
</style>






