keycode event及transition property應用

功能拆解

  1. keycode 和 audio binding
  2. audio可以重複撥放
  3. add playing class


Keycode

keyboardEvent中有keyCode這個屬性可以使用!

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

keyboard event

keyCode是鍵盤上的每一個鍵的代碼

透過keycode知道要讓畫面上對應的div加上動畫 & 對應的audio要播放


作者提供的對應表keycode info


Transitionend

transitionEvent 不同property是不同的event!

transitionend事件會在CSS transition完成時觸發!

transitionEvent


這6個transition事件來自於css

css style

transitionend的property為transform時,remove class playing


Code

 // 1. keycode 和 audio binding
 // 2. audio can play again
 // 3. add playing class 
 // 4. after transition, remove playing class

    function playSound(e) {
      const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
      const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
      if (!audio) return;
      audio.currentTime = 0;
      audio.play();
      key.classList.add('playing');
    }

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

    const keys = document.querySelectorAll('.key'); // 回傳NodeList
    keys.forEach(key => key.addEventListener('transitionend', removeTransition));
    window.addEventListener('keydown', playSound);


小結

  • <audio>
    • play()
    • currentTime
  • keyboardEvent
    • keyCode
  • transitiondend event

  • element
    • classList
      • add
      • remove
  • document
    • querySelectorAll
    • querySelector
      • [attrubute]