炫意html5
最早CSS3和HTML5移动技术网站之一

Javascript实现打鼓效果

这篇文章主要为大家详细介绍了Javascript实现打鼓效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Javascript实现打鼓效果的具体代码,供大家参考,具体内容如下

按住响应的键盘显示不同的声音

<div>
<div data-key="65">
<kbd>A</kbd>
<span>clap</span>
</div>
<div data-key="83">
<kbd>S</kbd>
<span>hihat</span>
</div>
<div data-key="68">
<kbd>D</kbd>
<span>kick</span>
</div>
<div data-key="70">
<kbd>F</kbd>
<span>openhat</span>
</div>
<div data-key="71">
<kbd>G</kbd>
<span>boom</span>
</div>
<div data-key="72">
<kbd>H</kbd>
<span>ride</span>
</div>
<div data-key="74">
<kbd>J</kbd>
<span>snare</span>
</div>
<div data-key="75">
<kbd>K</kbd>
<span>tom</span>
</div>
<div data-key="76">
<kbd>L</kbd>
<span>tink</span>
</div>
</div>
<audio data-key="65" src="https://www.jb51.net/article/sounds/clap.wav"></audio>
<audio data-key="83" src="https://www.jb51.net/article/sounds/hihat.wav"></audio>
<audio data-key="68" src="https://www.jb51.net/article/sounds/kick.wav"></audio>
<audio data-key="70" src="https://www.jb51.net/article/sounds/openhat.wav"></audio>
<audio data-key="71" src="https://www.jb51.net/article/sounds/boom.wav"></audio>
<audio data-key="72" src="https://www.jb51.net/article/sounds/ride.wav"></audio>
<audio data-key="74" src="https://www.jb51.net/article/sounds/snare.wav"></audio>
<audio data-key="75" src="https://www.jb51.net/article/sounds/tom.wav"></audio>
<audio data-key="76" src="https://www.jb51.net/article/sounds/tink.wav"></audio>

css部分:

html {
font-size: 10px;
background: url('../img/background.jpg') bottom center;
background-size: cover;
}
body,html {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.keys {
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
justify-content: center;
}
.key {
border: .4rem solid black;
border-radius: .5rem;
margin: 1rem;
font-size: 1.5rem;
padding: 1rem .5rem;
transition: all .07s ease;
width: 10rem;
text-align: center;
color: white;
background: rgba(0,0,0,0.4);
text-shadow: 0 0 .5rem black;
}
.playing {
transform: scale(1.1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
kbd {
display: block;
font-size: 4rem;
}
.sound {
font-size: 1.2rem;
text-transform: uppercase;
letter-spacing: .1rem;
color: #ffc600;
}

第一步实现按下键盘实现,声音的播放

window.addEventListener("keydown",function(e){
console.log(e.keyCode);
const audio=document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key=document.querySelector(`div[data-key="${e.keyCode}"]`)
//每次播放完初始化
if (!audio) return;
audio.currentTime = 0;
audio.play();
key.classList.add('playing');
setTimeout(function(){
key.classList.remove('playing');
},70);
//按键之后移出效果
})

keyCode对应图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持炫H5(xyhtml5.com)。

炫意HTML5 » Javascript实现打鼓效果

CSS3教程HTML5教程