1. Overview

Challenge & starter files: Advent of JS

Full codes: nilstarbb/advent-of-js/4-computer-keyboard

Live Demo: 04 - Eyes on the Screen || Advent of JavaScript

Preview:

computer-keyboard.gif

2. Details

Users should be able to:

  • See the computer keyboard centered on the page
  • A random letter will start to jiggle.
  • The user should type the same key that’s jiggling and it will stop.
  • A new, random key will start jiggling

3. Coding

逻辑大致如下:

  1. getElementsByClassName("key") 选取全部按键 keys
  2. keys 中随机抽取一个按键添加 .jiggle class。
  3. 绑定用户的 keydown,使用 e.preventDefault() 阻止默认事件执行。
  4. 对比用户所按按键与具有 .jiggle class 的按键的字符,若一致,则移除 .jiggle
  5. 重复步骤2。
const keys = document.getElementsByClassName("key");

const keyDown = (e) => {
  e.preventDefault();
  const jiggleKey = document.getElementsByClassName("jiggle")[0];
  if (jiggleKey.dataset.key == e.key.toUpperCase()) {
    jiggleKey.classList.remove("jiggle");
    keys[Math.floor(Math.random() * keys.length)].classList.add('jiggle');
  }
};

window.onkeydown = keyDown;

延伸阅读: