vue实现红包跳动
Vue 实现红包跳动效果
红包跳动效果可以通过 CSS 动画和 Vue 的动态绑定实现。以下是具体实现方法:
动画基础实现
定义红包跳动的 CSS 关键帧动画:
@keyframes jump {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
}
.red-packet {
width: 100px;
height: 120px;
background-color: #e74c3c;
border-radius: 5px;
position: relative;
animation: jump 0.5s infinite alternate;
}
Vue 组件实现
创建 Vue 组件并绑定动画:
<template>
<div class="red-packet-container">
<div
v-for="(packet, index) in packets"
:key="index"
class="red-packet"
:style="{
left: `${packet.position.x}px`,
top: `${packet.position.y}px`,
animationDelay: `${index * 0.1}s`
}"
@click="collectPacket(index)"
>
<span class="money">¥{{ packet.amount }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
packets: [
{ amount: 5, position: { x: 50, y: 100 }, collected: false },
{ amount: 10, position: { x: 150, y: 200 }, collected: false },
{ amount: 20, position: { x: 250, y: 150 }, collected: false }
]
}
},
methods: {
collectPacket(index) {
if (!this.packets[index].collected) {
this.packets[index].collected = true;
// 这里可以添加收集动画或其他逻辑
}
}
}
}
</script>
<style>
.red-packet-container {
position: relative;
width: 100%;
height: 300px;
}
.red-packet {
position: absolute;
width: 60px;
height: 80px;
background-color: #e74c3c;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
animation: jump 0.5s infinite alternate;
}
.money {
color: gold;
font-weight: bold;
font-size: 16px;
}
</style>
进阶效果优化
添加随机位置和大小:
generatePackets(count) {
const packets = [];
for (let i = 0; i < count; i++) {
packets.push({
amount: Math.floor(Math.random() * 50) + 1,
position: {
x: Math.random() * (window.innerWidth - 100),
y: Math.random() * (window.innerHeight - 150)
},
size: Math.random() * 0.5 + 0.8,
collected: false
});
}
return packets;
}
添加收集动画:
@keyframes collect {
0% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(3);
opacity: 0;
}
}
.collected {
animation: collect 0.5s forwards !important;
}
注意事项
- 确保动画性能优化,使用
transform和opacity这些不会触发重排的属性 - 移动端适配需要考虑触摸事件
- 大量红包时使用虚拟滚动优化性能
- 可以添加音效增强用户体验
这种方法结合了 Vue 的响应式特性和 CSS 动画,可以轻松实现红包跳动效果,并且可以根据需求扩展更多功能。







