用vue实现敲瓶子
实现思路
使用Vue实现敲瓶子效果,可以通过监听鼠标或触摸事件触发动画和音效。核心在于利用Vue的数据绑定和事件处理能力,结合CSS动画和HTML5音频API。
基本结构
创建Vue组件,包含瓶子元素和音频元素。瓶子用CSS绘制或使用图片,音频元素加载敲击音效。

<template>
<div class="bottle" @click="hitBottle"></div>
<audio ref="audio" src="bottle-hit.mp3" preload="auto"></audio>
</template>
动画效果
点击时触发CSS动画,通过动态添加/移除类名实现:
.bottle {
width: 50px;
height: 100px;
background: #00a8ff;
position: relative;
transition: transform 0.1s;
}
.bottle.hit {
transform: rotate(10deg);
}
交互逻辑
在Vue方法中处理点击事件,播放动画和音效:

methods: {
hitBottle() {
const bottle = this.$el.querySelector('.bottle');
const audio = this.$refs.audio;
bottle.classList.add('hit');
audio.currentTime = 0;
audio.play();
setTimeout(() => {
bottle.classList.remove('hit');
}, 100);
}
}
增强效果
可以添加多个瓶子并随机生成不同音高:
data() {
return {
bottles: Array(5).fill().map((_, i) => ({
id: i,
pitch: 0.8 + Math.random() * 0.4
}))
}
}
<template>
<div
v-for="bottle in bottles"
:key="bottle.id"
class="bottle"
@click="hitBottle(bottle)"
></div>
</template>
hitBottle(bottle) {
const audio = this.$refs.audio;
audio.playbackRate = bottle.pitch;
// 其余动画逻辑...
}
移动端支持
添加触摸事件支持:
<div
class="bottle"
@click="hitBottle"
@touchstart="hitBottle"
></div>
完整组件示例
<template>
<div class="bottle-container">
<div
v-for="bottle in bottles"
:key="bottle.id"
class="bottle"
@click="hitBottle(bottle)"
@touchstart="hitBottle(bottle)"
></div>
<audio ref="audio" src="bottle-hit.mp3" preload="auto"></audio>
</div>
</template>
<script>
export default {
data() {
return {
bottles: Array(5).fill().map((_, i) => ({
id: i,
pitch: 0.8 + Math.random() * 0.4
}))
}
},
methods: {
hitBottle(bottle) {
const el = event.target;
const audio = this.$refs.audio;
el.classList.add('hit');
audio.playbackRate = bottle.pitch;
audio.currentTime = 0;
audio.play();
setTimeout(() => {
el.classList.remove('hit');
}, 100);
}
}
}
</script>
<style>
.bottle-container {
display: flex;
justify-content: space-around;
padding: 20px;
}
.bottle {
width: 40px;
height: 80px;
background: linear-gradient(to bottom, #00a8ff, #0097e6);
border-radius: 5px 5px 15px 15px;
position: relative;
cursor: pointer;
transition: transform 0.1s;
}
.bottle:after {
content: '';
position: absolute;
top: -10px;
left: 15px;
width: 10px;
height: 15px;
background: #00a8ff;
border-radius: 5px 5px 0 0;
}
.bottle.hit {
transform: rotate(10deg);
}
</style>
注意事项
- 音效文件需要准备合适的敲击音效
- 移动端需要考虑触摸反馈延迟
- 动画时间需要与音效时长匹配
- 多个瓶子同时敲击时需要处理音频重叠






