vue实现呼吸灯
实现呼吸灯效果的方法
呼吸灯效果可以通过CSS动画或JavaScript动态控制实现。以下是两种常见的实现方式:
使用CSS动画实现
通过CSS的@keyframes定义透明度或亮度的周期性变化,结合Vue的模板绑定类名或样式。

<template>
<div class="breathing-light"></div>
</template>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
animation: breathe 3s infinite;
}
@keyframes breathe {
0% { opacity: 0.3; }
50% { opacity: 1; }
100% { opacity: 0.3; }
}
</style>
使用JavaScript动态控制
通过Vue的响应式数据结合requestAnimationFrame或setInterval动态修改样式属性。

<template>
<div
class="breathing-light"
:style="{ opacity: currentOpacity }"
></div>
</template>
<script>
export default {
data() {
return {
currentOpacity: 0.3,
direction: 1,
speed: 0.01
};
},
mounted() {
this.animate();
},
methods: {
animate() {
this.currentOpacity += this.speed * this.direction;
if (this.currentOpacity >= 1 || this.currentOpacity <= 0.3) {
this.direction *= -1;
}
requestAnimationFrame(this.animate);
}
}
};
</script>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
}
</style>
结合Vue过渡效果
使用Vue的<transition>组件和CSS过渡属性实现平滑的呼吸效果。
<template>
<transition name="breath">
<div v-if="show" class="breathing-light"></div>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
};
},
mounted() {
setInterval(() => {
this.show = !this.show;
}, 1500);
}
};
</script>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
}
.breath-enter-active, .breath-leave-active {
transition: opacity 1.5s;
}
.breath-enter, .breath-leave-to {
opacity: 0.3;
}
</style>
使用第三方库(如GSAP)
通过GSAP等动画库实现更复杂的呼吸效果。
<template>
<div ref="light" class="breathing-light"></div>
</template>
<script>
import { gsap } from 'gsap';
export default {
mounted() {
gsap.to(this.$refs.light, {
opacity: 0.3,
duration: 1.5,
repeat: -1,
yoyo: true
});
}
};
</script>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
}
</style>
注意事项
- 性能优化:CSS动画通常性能更好,优先考虑纯CSS方案。
- 兼容性:检查
requestAnimationFrame和CSS动画的浏览器支持情况。 - 参数调整:呼吸速度(
animation-duration或speed)和透明度范围可根据需求调整。






