用vue写一个钢琴界面
时间: 2024-05-01 10:23:25 浏览: 8
好的,下面是一个简单的钢琴界面的Vue组件代码:
```vue
<template>
<div class="piano">
<div class="white-keys">
<div v-for="(key, index) in whiteKeys" :key="index" class="white-key" :class="{active: activeKey === key}" @mousedown="playSound(key)" @mouseup="stopSound(key)"></div>
</div>
<div class="black-keys">
<div v-for="(key, index) in blackKeys" :key="index" class="black-key" :class="{active: activeKey === key}" @mousedown="playSound(key)" @mouseup="stopSound(key)"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
whiteKeys: ['C', 'D', 'E', 'F', 'G', 'A', 'B', 'C2'],
blackKeys: ['C#', 'D#', '', 'F#', 'G#', 'A#', ''],
activeKey: ''
}
},
methods: {
playSound(key) {
this.activeKey = key;
const audio = new Audio(`/sounds/${key}.mp3`);
audio.play();
},
stopSound(key) {
this.activeKey = '';
}
}
}
</script>
<style scoped>
.piano {
display: flex;
justify-content: space-between;
align-items: flex-end;
width: 600px;
height: 200px;
background-color: #d4d4d4;
border-radius: 10px;
padding: 20px;
}
.white-keys {
display: flex;
justify-content: space-between;
width: calc(100% - 10px);
height: 100%;
}
.white-key {
width: calc(100% / 7 - 2px);
height: 80%;
background-color: #fff;
border: 1px solid #000;
border-radius: 10px;
cursor: pointer;
}
.white-key.active {
background-color: #000;
color: #fff;
}
.black-keys {
display: flex;
justify-content: space-between;
width: calc(100% - 10px);
height: 60%;
margin-left: -25%;
}
.black-key {
width: calc(100% / 14 - 2px);
height: 60%;
background-color: #000;
border: 1px solid #000;
border-radius: 10px;
cursor: pointer;
position: relative;
margin: 0 2px;
}
.black-key.active {
background-color: #fff;
color: #000;
}
.black-key:before {
content: '';
width: 60%;
height: 50%;
background-color: #000;
border-radius: 10px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
.black-key:nth-child(odd):before {
left: auto;
right: 0;
}
</style>
```
需要注意的是,该组件需要与相应的音频文件配合使用。你需要在项目根目录下创建一个名为`sounds`的文件夹,将所有的音频文件放在里面,并将文件名与组件中的`whiteKeys`和`blackKeys`数组中的元素对应起来。