vue实现停止动画
停止 CSS 动画
在 Vue 中停止 CSS 动画可以通过移除或修改元素的 class 或内联样式来实现。CSS 动画通常通过 @keyframes 或 transition 实现,移除相关类名即可停止动画。
<template>
<div :class="{ 'animate': isAnimating }" @click="toggleAnimation">
点击停止动画
</div>
</template>
<script>
export default {
data() {
return {
isAnimating: true
};
},
methods: {
toggleAnimation() {
this.isAnimating = !this.isAnimating;
}
}
};
</script>
<style>
.animate {
animation: spin 2s infinite linear;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
停止 JavaScript 动画
对于使用 JavaScript 实现的动画(如 requestAnimationFrame 或第三方库如 GSAP),需要手动取消动画帧或调用停止方法。

<template>
<div ref="box" @click="stopAnimation">点击停止动画</div>
</template>
<script>
export default {
data() {
return {
animationId: null,
position: 0
};
},
mounted() {
this.startAnimation();
},
methods: {
startAnimation() {
const animate = () => {
this.position += 1;
this.$refs.box.style.transform = `translateX(${this.position}px)`;
this.animationId = requestAnimationFrame(animate);
};
this.animationId = requestAnimationFrame(animate);
},
stopAnimation() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
}
};
</script>
停止第三方动画库
如果使用 GSAP、Anime.js 等第三方动画库,通常需要调用其提供的停止或销毁方法。

<template>
<div ref="target" @click="stopAnimation">点击停止动画</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
data() {
return {
tween: null
};
},
mounted() {
this.tween = gsap.to(this.$refs.target, {
x: 100,
duration: 2,
repeat: -1
});
},
methods: {
stopAnimation() {
if (this.tween) {
this.tween.kill();
this.tween = null;
}
}
}
};
</script>
停止 Vue 过渡动画
Vue 的 <transition> 组件可以通过绑定 v-if 或 v-show 动态控制动画的启停。
<template>
<button @click="show = !show">切换动画</button>
<transition name="fade">
<div v-if="show">内容</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
};
}
};
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
动态绑定样式停止动画
通过动态绑定内联样式或类名,可以灵活控制动画的播放状态。
<template>
<div
:style="{ animationPlayState: isPaused ? 'paused' : 'running' }"
class="spin"
@click="isPaused = !isPaused"
>
点击暂停/播放
</div>
</template>
<script>
export default {
data() {
return {
isPaused: false
};
}
};
</script>
<style>
.spin {
animation: spin 2s infinite linear;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>






