Demo:
https://raindot.github.io/Javascript30/01-JavaScriptDrumKit/myindex.html
把Event Listener掛在window上
window.addEventListener('keypress', playSound);
按下按鍵時會執行的動作
function playSound(e){
const audio = document.querySelector(`audio[data-key="${e.keyCode}"`);
//如果選不到audio元件就結束
if (!audio) return;
audio.currentTime = 0;
audio.play();
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
key.classList.add('playing');
}
讓按下去發光的效果隨著放開鍵盤(結束事件)而消失,達成閃一下的效果
const keys = document.querySelector(".keys");
keys.addEventListener('transitionend', removeTransition);
function removeTransition(e){
console.log(e.propertyName);
if (e.propertyName !== "transform") return;
e.target.classList.remove('playing');
}