用vue实现敲瓶子
实现敲瓶子动画的Vue组件
创建Vue组件实现敲击瓶子动画效果,需要结合CSS动画和用户交互事件。
组件模板结构
<template>
<div class="bottle-container">
<div
class="bottle"
:class="{ 'bottle-hit': isHit }"
@click="hitBottle"
>
<div class="bottle-neck"></div>
<div class="bottle-body"></div>
</div>
<div class="sound-indicator" v-if="showSound">
~~~
</div>
</div>
</template>
组件脚本逻辑
<script>
export default {
data() {
return {
isHit: false,
showSound: false
}
},
methods: {
hitBottle() {
this.isHit = true;
this.showSound = true;
setTimeout(() => {
this.isHit = false;
}, 500);
setTimeout(() => {
this.showSound = false;
}, 1000);
}
}
}
</script>
样式设计
<style scoped>
.bottle-container {
position: relative;
display: inline-block;
}
.bottle {
position: relative;
width: 60px;
height: 120px;
cursor: pointer;
transition: transform 0.1s;
}
.bottle-neck {
position: absolute;
top: 0;
left: 20px;
width: 20px;
height: 30px;
background: #4CAF50;
border-radius: 5px 5px 0 0;
}
.bottle-body {
position: absolute;
top: 30px;
width: 60px;
height: 90px;
background: #4CAF50;
border-radius: 0 0 10px 10px;
}
.bottle-hit {
animation: hit 0.5s ease;
}
.sound-indicator {
position: absolute;
top: -30px;
left: 70px;
font-size: 24px;
animation: fade 1s forwards;
}
@keyframes hit {
0% { transform: rotate(0deg); }
25% { transform: rotate(-15deg); }
50% { transform: rotate(10deg); }
75% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
@keyframes fade {
0% { opacity: 1; }
100% { opacity: 0; }
}
</style>
增强交互效果
可以添加声音效果增强体验,需要引入音频文件:
// 在methods中修改hitBottle方法
hitBottle() {
this.isHit = true;
this.showSound = true;
// 播放声音
const audio = new Audio(require('@/assets/bottle-hit.mp3'));
audio.play();
setTimeout(() => {
this.isHit = false;
}, 500);
setTimeout(() => {
this.showSound = false;
}, 1000);
}
多瓶子排列实现
创建多个瓶子实例:
<template>
<div class="bottle-row">
<Bottle v-for="(bottle, index) in 5" :key="index" />
</div>
</template>
<style>
.bottle-row {
display: flex;
gap: 20px;
}
</style>
响应式设计
添加响应式尺寸调整:
@media (max-width: 600px) {
.bottle {
width: 40px;
height: 80px;
}
.bottle-neck {
width: 15px;
height: 20px;
left: 12.5px;
}
.bottle-body {
top: 20px;
width: 40px;
height: 60px;
}
}






