Day1-Drum Kit


Posted by Jasper on 2022-06-02

第一天要做到的事情:

透過對應的按鍵,做出聲音及效果
學習的內容:

  • Dom選取HTML標籤
  • addEventListener

完整程式碼:

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

  audio.currentTime = 0;
  audio.play();
}

function removeCss(e) {
  const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
  if (!key) return;
  key.classList.remove("playing");
}

window.addEventListener("keydown", playSound);
window.addEventListener("keyup", removeCss);

第一個function:
function playSound(e) {
  const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
  if (!audio) return;
  key.classList.add("playing");

  audio.currentTime = 0;
  audio.play();
}
先介紹一下html5的自定義屬性<div data-*></div>

*可以替代任何字母,有兩個限制:

  1. 不可為大寫
  2. 至少有一個字符
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
  if (!audio) return;

document.querySelector可以選取html內的標籤,這邊使用ES6的新功能"``",可以透過
${}抓到不同的值,if (!audio),則是判斷如果不是HTML內所設定的data-key時,
則直接return結束。

key.classList.add("playing");

  audio.currentTime = 0;
  audio.play();

key.classList.add("playing"); : 原本想用toggle()直接抓className,但發現好像沒辦法。
audio.currentTime = 0; : 讓audio/video回到對應的秒數(這樣才可以連續按同一個按鍵都會有聲音)。
audio.play(); : 播放音效。


第二個function:
function removeCss(e) {
  const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
  if (!key) return;
  key.classList.remove("playing");
}

會有這個function 純粹是發現如果一直按住按鍵不放,css會直接壞掉,所以額外加了window.addEventListener("keyup", removeCss);防止css壞掉。

最後
window.addEventListener("keydown", playSound);
window.addEventListener("keyup", removeCss);

window.addEventListener(); : 監聽事件變化後做處理,window代表了瀏覽器的頁面,所以處在此頁面時,可以抓取相對應要做的事情,也可以把要做的事情直接寫在裡面。

以上是JS30第一天的內容。










Related Posts

C++ : namespace (1)

C++ : namespace (1)

Lidemy HTTP Challenge 全破流程與心得

Lidemy HTTP Challenge 全破流程與心得

[Note] HTML簡介

[Note] HTML簡介


Comments