vue实现半场动画
Vue 实现半场动画
在 Vue 中实现半场动画通常指的是动画执行到一半时停止或改变状态。可以通过 Vue 的过渡系统或第三方动画库(如 GSAP)实现。
使用 Vue 过渡
Vue 提供了 <transition> 和 <transition-group> 组件,结合 CSS 过渡或动画类名,可以控制动画的中间状态。
<template>
<div>
<button @click="toggle">Toggle Animation</button>
<transition name="halfway">
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
};
},
methods: {
toggle() {
this.show = !this.show;
}
}
};
</script>
<style>
.halfway-enter-active {
animation: slide-in 0.5s;
}
.halfway-leave-active {
animation: slide-in 0.5s reverse;
}
@keyframes slide-in {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(0);
opacity: 1;
}
100% {
transform: translateX(100%);
opacity: 0;
}
}
.box {
width: 100px;
height: 100px;
background: #42b983;
}
</style>
使用 GSAP 控制动画
GSAP 提供了更精细的动画控制,可以通过 pause() 或 seek() 方法实现半场动画。
<template>
<div>
<button @click="startAnimation">Start Animation</button>
<button @click="pauseAtHalfway">Pause at Halfway</button>
<div ref="box" class="box"></div>
</div>
</template>
<script>
import { gsap } from "gsap";
export default {
methods: {
startAnimation() {
gsap.to(this.$refs.box, {
x: 200,
duration: 2,
opacity: 0
});
},
pauseAtHalfway() {
const animation = gsap.getTweensOf(this.$refs.box)[0];
if (animation) {
animation.pause();
animation.seek(1); // 1 秒时暂停(假设总时长为 2 秒)
}
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background: #42b983;
}
</style>
使用 JavaScript 钩子
Vue 的过渡系统提供了 JavaScript 钩子(如 @enter 和 @leave),可以在动画过程中插入自定义逻辑。
<template>
<div>
<button @click="toggle">Toggle Animation</button>
<transition
@enter="enter"
@leave="leave"
:css="false"
>
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
};
},
methods: {
toggle() {
this.show = !this.show;
},
enter(el, done) {
const animation = el.animate(
[
{ transform: "translateX(-100%)", opacity: 0 },
{ transform: "translateX(0)", opacity: 1 },
{ transform: "translateX(100%)", opacity: 0 }
],
{
duration: 1000
}
);
animation.onfinish = done;
// 半场停止
setTimeout(() => {
animation.pause();
}, 500);
},
leave(el, done) {
const animation = el.animate(
[
{ transform: "translateX(0)", opacity: 1 },
{ transform: "translateX(100%)", opacity: 0 }
],
{
duration: 1000
}
);
animation.onfinish = done;
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background: #42b983;
}
</style>
总结
- Vue 过渡系统适合简单的半场动画,通过 CSS 或 JavaScript 钩子控制。
- GSAP 提供更强大的动画控制,适合复杂场景。
- JavaScript 钩子可以在动画过程中插入自定义逻辑,实现精确控制。







