vue实现颜色闪烁
Vue 实现颜色闪烁的方法
使用 CSS 动画和 Vue 动态绑定
通过 Vue 的动态样式绑定结合 CSS 动画实现颜色闪烁效果。定义一个 CSS 动画,通过 :style 或 :class 绑定到元素上。
<template>
<div :style="{ animation: isBlinking ? 'blink 1s infinite' : '' }">
闪烁的文字
</div>
</template>
<script>
export default {
data() {
return {
isBlinking: true
}
}
}
</script>
<style>
@keyframes blink {
0%, 100% { background-color: red; }
50% { background-color: transparent; }
}
</style>
使用 setInterval 控制样式切换
通过 JavaScript 定时器动态切换样式类或内联样式,实现更灵活的控制。

<template>
<div :class="{ 'blink-color': isBlinking }">
闪烁的文字
</div>
</template>
<script>
export default {
data() {
return {
isBlinking: false
}
},
mounted() {
setInterval(() => {
this.isBlinking = !this.isBlinking
}, 500)
}
}
</script>
<style>
.blink-color {
background-color: yellow;
}
</style>
使用第三方库(如 vue-animate-css)
通过第三方动画库快速实现高级动画效果,例如 vue-animate-css。
安装库:

npm install vue-animate-css
使用示例:
<template>
<div class="animated infinite flash">
闪烁的文字
</div>
</template>
<script>
import 'vue-animate-css'
export default {}
</script>
通过计算属性动态生成样式
结合计算属性动态生成闪烁样式,适合需要复杂逻辑的场景。
<template>
<div :style="blinkStyle">
闪烁的文字
</div>
</template>
<script>
export default {
data() {
return {
blinkState: false
}
},
computed: {
blinkStyle() {
return {
backgroundColor: this.blinkState ? 'red' : 'blue',
transition: 'background-color 0.5s'
}
}
},
mounted() {
setInterval(() => {
this.blinkState = !this.blinkState
}, 500)
}
}
</script>
注意事项
- 性能优化:频繁的样式变动可能引发重绘,建议使用
requestAnimationFrame替代setInterval。 - 兼容性:CSS 动画在绝大多数现代浏览器中支持良好,但需注意前缀问题。
- 清除定时器:在组件销毁时清除定时器以避免内存泄漏。
beforeDestroy() {
clearInterval(this.timer)
}






