我用JavaScript写了一个键盘架子鼓
前言
在数字化时代,创建高效、交互丰富的网页应用是前端开发者的重要任务。本篇文章将通过一个具体的示例项目,深入探讨如何结合HTML5、CSS3与JavaScript,构建一个具备实时键盘响应、音效播放及良好用户体验的富媒体应用。我们将重点关注代码结构的优化、布局效率以及性能提升策略。
HTML结构:定义交互元素
深色版本
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Rich Web Application With HTML5</title>
7 <link rel="stylesheet" href="./common.css">
8</head>
9<body>
10 <div class="keys">
11 <!-- 键盘元素 -->
12 <div class="key" data-key="65">
13 <div class="title">A</div>
14 <span class="sound">镲</span>
15 </div>
16 <!-- 更多键位... -->
17 </div>
18 <script src="./common.js"></script>
19</body>
20</html>
- 在HTML部分,我们定义了一个名为
.keys
的容器,其中包含了多个.key
元素,每个元素都有一个数据属性data-key
用于绑定键盘事件,以及.title
和.sound
元素用于显示和存储音效信息。
CSS样式:优化视觉与布局
html {
font-size: 10px;
background: url('./background.jpg') bottom center;
background-size: cover;
}
html, body {
height: 100%;
}
.keys {
display: flex;
min-height: 100%;
align-items: center;
justify-content: center;
}
.key {
border: 4px solid black;
border-radius: 5px;
margin: 10px;
font-size: 15px;
padding: 10px 5px;
transition: all .7s ease;
width: 100px;
text-align: center;
color: white;
background: rgba(0,0,0,.4);
text-shadow: 0 0 5px black;
}
.key .title {
font-size: 40px;
}
.sound {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 1px;
color: #ffc600;
}
.playing {
transform: scale(1.1);
border-color: #ffc600;
box-shadow: 0 0 5px #ffc600;
}
- CSS通过Flexbox实现了按键的居中布局,并使用
.playing
类来增加按键被激活时的视觉效果。同时,transition
属性使得动画过渡更加平滑。
JavaScript交互:实现动态响应
const keys = document.querySelectorAll('.key');
window.addEventListener('keydown', playSound);
window.addEventListener('keyup', removeTransition);
function playSound(event) {
const keyCode = event.keyCode;
const ele = document.querySelector(`.key[data-key="${keyCode}"]`);
if (ele) {
ele.classList.add('playing');
const soundName = ele.querySelector('.sound').textContent;
const audio = new Audio(`./sound/${soundName}.mp3`);
audio.play();
setTimeout(removeTransition.bind(ele), 800);
}
}
function removeTransition() {
this.classList.remove('playing');
}
JavaScript代码监听键盘事件,当按键被按下时,播放相应的音效并添加
.playing
类;当按键释放时,通过removeTransition
函数移除该类,确保视觉反馈与音效同步。
- 这里给了A和S的实例,后面的效果可以在html里修改
小结
键盘点击事件和音效在游戏中非常常见,大佬之路就从架子鼓开始吧
转载自:https://juejin.cn/post/7388311581657808948