vue实现呼吸灯
实现呼吸灯效果
在Vue中实现呼吸灯效果可以通过CSS动画和Vue的动态绑定结合完成。呼吸灯通常表现为元素亮度或透明度周期性变化。
使用CSS动画实现
创建一个周期性改变透明度的CSS动画,通过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 ease-in-out;
}
@keyframes breathe {
0%, 100% {
opacity: 0.5;
transform: scale(0.9);
}
50% {
opacity: 1;
transform: scale(1.1);
}
}
</style>
使用Vue动态控制
通过Vue的响应式数据控制样式属性,结合JavaScript定时器实现更灵活的控制。

<template>
<div
class="breathing-light"
:style="{
opacity: currentOpacity,
transform: `scale(${currentScale})`
}"
></div>
</template>
<script>
export default {
data() {
return {
currentOpacity: 0.5,
currentScale: 0.9,
animationInterval: null
}
},
mounted() {
this.startAnimation()
},
beforeDestroy() {
clearInterval(this.animationInterval)
},
methods: {
startAnimation() {
let direction = 1
const speed = 0.02
this.animationInterval = setInterval(() => {
this.currentOpacity += speed * direction
this.currentScale += speed * direction * 0.2
if(this.currentOpacity >= 1 || this.currentOpacity <= 0.5) {
direction *= -1
}
}, 50)
}
}
}
</script>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
transition: opacity 0.1s ease, transform 0.1s ease;
}
</style>
使用第三方动画库
考虑使用动画库如GSAP或Animate.css实现更复杂的呼吸效果。
<template>
<div ref="lightElement" class="breathing-light"></div>
</template>
<script>
import gsap from 'gsap'
export default {
mounted() {
gsap.to(this.$refs.lightElement, {
opacity: 0.5,
scale: 0.9,
duration: 1.5,
repeat: -1,
yoyo: true,
ease: "sine.inOut"
})
}
}
</script>
<style>
.breathing-light {
width: 100px;
height: 100px;
background-color: #42b983;
border-radius: 50%;
}
</style>
实现带颜色的呼吸灯
扩展基本呼吸灯效果,加入颜色变化。
<template>
<div class="color-breathing-light"></div>
</template>
<style>
.color-breathing-light {
width: 100px;
height: 100px;
border-radius: 50%;
animation: colorBreathe 4s infinite;
}
@keyframes colorBreathe {
0% {
background-color: #42b983;
opacity: 0.5;
transform: scale(0.9);
}
50% {
background-color: #ff7e67;
opacity: 1;
transform: scale(1.1);
}
100% {
background-color: #42b983;
opacity: 0.5;
transform: scale(0.9);
}
}
</style>






