[JS30] Day01: JavaScript Drum Kit
CSS
加上.playing的 class 之後,會有黃色邊框放大按下的效果
.key {
transition: all 0.07s ease;
}
.playing {
transform: scale(1.1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
JavaScript
window 為視窗元素,透過keydown來偵測按鍵按下事件,按下時會呼叫 playSound 函式。
playSound 函式中,我們透過querySelector抓取元素的屬性audio[data-key]等於keydown事件中的 keycode 的 audio 元素和.key 的元素,來去操作。
該 key 的 class 加入playing時,因為transition為 0.07s,會有個過渡的效果。
最後在所有的.key 元素上加入transitionend的監聽器,來去移除playing的 class。
function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
if (!audio) return;
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
audio.currentTime = 0; // 重置聲音
audio.play(); // 播放聲音
key.classList.add("playing"); // 加入playing的class
}
window.addEventListener("keydown", playSound);
function removeTransition(e) {
if (e.propertyName != "transform") return;
this.classList.remove("playing");
}
const keys = document.querySelectorAll(".key");
keys.forEach((key) => key.addEventListener("transitionend", removeTransition));