来来来,今天咱们来谈钢琴,制作一个小钢琴练习练习。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>钢琴</title>
<style>
html{
height: 100%;
}
body{
margin: 0;
height: 100%;
/*渐变色*/
background:radial-gradient(#666,#000);
/*弹性布局*/
display: flex;
justify-content: center;
align-items: center;
}
main{
width: 100%;
height: 100%;
border: 18px solid #333;
/*max表示最大 也就是说限制宽最大为800px*/
max-width: 800px;
max-height: 400px;
border-top-width: 40px;
border-bottom-width: 13px;
background-image: url(keys.png);
background-size: 100% 100%;
border-radius: 10px;
display: flex;
}
div{
height: 100%;
flex-grow: 1;
}
div:active,div.active{
background-image: linear-gradient(rgba(255,255,255,0),rgba(150,150,150,0.3));
}
</style>
</head>
<body>
<audio src="notes/1.oga"></audio>
<audio src="notes/2.oga"></audio>
<audio src="notes/3.oga"></audio>
<audio src="notes/4.oga"></audio>
<audio src="notes/5.oga"></audio>
<audio src="notes/6.oga"></audio>
<audio src="notes/7.oga"></audio>
<audio src="notes/8.oga"></audio>
<audio src="notes/9.oga"></audio>
<main>
<div onmousedown="play(0)"></div>
<div onmousedown="play(1)"></div>
<div onmousedown="play(2)"></div>
<div onmousedown="play(3)"></div>
<div onmousedown="play(4)"></div>
<div onmousedown="play(5)"></div>
<div onmousedown="play(6)"></div>
<div onmousedown="play(7)"></div>
<div onmousedown="play(8)"></div>
</main>
<script>
var audios = document.querySelectorAll('audio')
var divs =document.querySelectorAll('div')
var code = 0
function play(index){
var audio = audios[index]
// 加载
audio.load()
// 播放
audio.play()
}
// onkeydown表示键盘按下去的时候触发的事件
window.onkeydown = function(ev){
console.log(ev.keyCode)
if(code != ev.keyCode){
code = ev.keyCode
if(code >=49 && code <= 57){
play(code - 49)
divs[code - 49].classList.add('active')
}
}
}
// onkeyup表示键盘松开时发生的事件
window.onkeyup = function(){
code = 0;
for(var i = 0 ;i< divs.length;i++){
divs[i].classList.remove('active')
}
}
</script>
</body>
</html>
另附上两首钢琴曲:
两只老虎:1231 1231 345 345 565431 565431 312 312
小星星:1155665 4433221 5544332 5544332 1155665 4433221
更多曲子请在360导航的首页那里获取。
素材下载:2017-03-10 钢琴