Piano Kit

REF: JavaScript30

音樂素材:魔王魂

説明

按下特定鍵盤按鈕,會出現鋼琴音與特效

先備知識

範例

.container
 .infos
 h1 Piano Keyboard
 .keys
 button.key(data-key="65")
 kbd A
 span C
 button.key(data-key="83")
 kbd S
 span D
 button.key(data-key="68")
 kbd D
 span E
 button.key(data-key="70")
 kbd F
 span F
 button.key(data-key="71")
 kbd G
 span G
 button.key(data-key="72")
 kbd H
 span A
 button.key(data-key="74")
 kbd J
 span B
 button.key(data-key="75")
 kbd K
 span C


audio(data-key="65" src="https://goo.gl/r6zBRo")
audio(data-key="83" src="https://goo.gl/ymMuIO")
audio(data-key="68" src="https://goo.gl/kbSq41")
audio(data-key="70" src="https://goo.gl/2SDjv7")
audio(data-key="71" src="https://goo.gl/JVhfKe")
audio(data-key="72" src="https://goo.gl/sRnzrM")
audio(data-key="74" src="https://goo.gl/N1WJBh")
audio(data-key="75" src="https://goo.gl/Epfm4A")
*
 //border: 1px solid #000
 font-family: Lato

body,html
 margin: 0
 padding: 0
 position: relative

.container
 width: 100%
 height: 100%
 text-align: center
 top: 35vh
 position: absolute
 
.infos
 margin-left: auto
 margin-right: auto
 max-width: 1200px
 width: 800px
 
 h1
 text-align: center

.keys
 display: inline-block
 .key
 width: 75px
 height: 75px
 background-color: #f2f2e9
 border: 2px solid #90a955
 transition: all 0.07s
 vertical-align: top
 kbd
 font-size: 26px
 font-weight: 700
 display: block
 span
 font-size: 16px

.playing
 border-color: #24260f
 transform: scale(1.1)
 box-shadow: 0 0 5px #90a955
function playSound(e){
 
 //抓到特定的audio
 //const定義常數:保持不變的値,相對於var 變數
 const audio=document.querySelector(`audio[data-key="${e.keyCode}"]`);
 //抓到特定的piano key
 const key=document.querySelector(`.key[data-key="${e.keyCode}"]`);
 if(!audio) return; //stop the function from running all together
 //如果沒有上面的if, 按不是piano的按鍵,會出現null
 audio.currentTime=0; //rewind to the start
 
 audio.play();
 key.classList.add("playing");
 
}

function removeTransition(e){
 
 if(e.propertyName!=="transform") return;//skip it if it is not transform
 this.classList.remove("playing");
 
}

const keys=Array.from(document.querySelectorAll(".key"));
//forEach 陣列裡面所有東西都...
keys.forEach(key => key.addEventListener('transitionend', removeTransition));

window.addEventListener("keydown", playSound);

/*****************
點擊播放功能新增區域
******************/
keys.forEach(key => key.addEventListener("click", clickPlay));
/*↑效果等於這個↓的迴圈
for(i=0;i<9;i++){
 keys[i].addEventListener("click", clickPlay);
}
*/
function clickPlay(){
 var dataKey=this.getAttribute("data-key");
 const audio2=document.querySelector(`audio[data-key="${dataKey}"]`);
 audio2.currentTime=0;
 audio2.play();
 
 this.classList.add("playing");
}

CODEPEN

Leave a Reply

Your email address will not be published. Required fields are marked *