因為會忘,所以要寫下來

JS30:01_JavaScript Drum Kit

2 minutes to read

JavaScript Drum Kit (鍵盤打鼓)

摘要

  • 了解鍵盤監聽事件 keyCode(鍵盤數字代碼)
  • 鍵盤與聲音對應
  • 畫面顯示所按到的鍵 (更改樣式)

CSS 排版

此次排版主要是以 flex 為主 FLEX 速查小抄

查詢鍵盤數字代碼

window.addEventListener('keydown', function (e) {
  console.log(e.keyCode);
});

key code 速查


windows 監聽事件

function playSound(e) {
  const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
  //如果沒有audio這個元素 則返回
  if (!audio) return;
  audio.currentTime = 0;
  audio.play();
  key.classList.add('playing');
}

window.addEventListener('keydown', playSound);

es6 語法

  • cosnt 是 es6 裡新增的變數宣告 可參照 MDN-const
  • es6 語法糖
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
`字符串 ${變數}`;

// es6過去寫法
var audio = document.querySelector('audio[data-key="' + e.keyCode + '"]');

音效處理

當按下音效播放時 正在播放的音效 在還沒結束時 所按下的其他音效都會無效 因此需要設定重置撥放時間 audio.currentTime = 0


打完後 移除 css 所產生的樣式

function removeTransition(e) {
  if (e.propertyName !== 'transform') return;
  this.classList.remove('playing');
}

const keys = document.querySelectorAll('.key');
keys.forEach((key) => key.addEventListener('transitionend', removeTransition));

es6 語法

  • 箭頭函式
keys.forEach((key) => key.addEventListener('transitionend', removeTransition));

// 拆解開後
keys.forEach((key, val) => {
  key.addEventListener('transitionend', removeTransition);
});

// es6前寫法
keys.forEach(function (key, val) {
  key.addEventListener('transitionend', removeTransition);
});

forEach 可參照 MDN-Array.prototype.forEach()

transitionend 效果結束後觸發 MDN-transitionend

YOUTUBE 影片教學連結

對這篇文章有什麼想法嗎?

Copyright © 2023 Mandy. All rights reserved. Build with Astro