vue实现图标闪烁
使用 CSS 动画实现图标闪烁
在 Vue 中实现图标闪烁可以通过 CSS 动画或 JavaScript 定时器控制。以下是基于 CSS 动画的方法,性能更好且易于维护。
定义闪烁动画样式
在组件的 <style> 部分或全局 CSS 中定义一个闪烁动画:
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.blink-icon {
animation: blink 1.5s infinite;
}
在 Vue 组件中应用动画
将动画类绑定到图标元素上,例如使用 Font Awesome 或 SVG 图标:
<template>
<div>
<!-- Font Awesome 图标示例 -->
<i class="fas fa-star blink-icon"></i>
<!-- SVG 图标示例 -->
<svg class="blink-icon" viewBox="0 0 24 24">
<path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"/>
</svg>
</div>
</template>
通过动态类名控制闪烁
如果需要通过逻辑控制闪烁(如点击触发),可以使用 Vue 的动态类名绑定:
<template>
<div>
<i
class="fas fa-bell"
:class="{ 'blink-icon': isBlinking }"
@click="toggleBlink"
></i>
</div>
</template>
<script>
export default {
data() {
return {
isBlinking: false
};
},
methods: {
toggleBlink() {
this.isBlinking = !this.isBlinking;
}
}
};
</script>
使用 JavaScript 定时器(备选方案)
如果需更复杂的控制(如非均匀闪烁),可通过 setInterval 动态修改样式:
<template>
<div>
<i ref="icon" class="fas fa-heart"></i>
</div>
</template>
<script>
export default {
mounted() {
this.startBlink();
},
beforeDestroy() {
clearInterval(this.blinkTimer);
},
methods: {
startBlink() {
this.blinkTimer = setInterval(() => {
this.$refs.icon.style.opacity =
this.$refs.icon.style.opacity === '0.3' ? '1' : '0.3';
}, 500);
}
}
};
</script>
注意事项
- 性能优化:CSS 动画比 JavaScript 定时器更高效,优先推荐。
- 浏览器兼容性:
@keyframes和animation支持所有现代浏览器。 - 自定义参数:调整
animation-duration或keyframes中的百分比可改变闪烁频率和效果。







