[miniProjects] 11_Event KeyCodes

๋ณด๋ฆฌยท2023๋…„ 6์›” 16์ผ
0

miniProjects

๋ชฉ๋ก ๋ณด๊ธฐ
12/47

11_Event KeyCodes

๐Ÿ’ป ์ฃผ์ œ : ํ‚ค๋ณด๋“œ ํ‚ค๋ฅผ ๋ˆŒ๋ €์„ ๋•Œ ํ‚ค ๋ฒ„ํŠผ๊ณผ ํ‚ค์ฝ”๋“œ๋ฅผ ๋ณด์—ฌ์คŒ.

  • keydown ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ.


window.addEventListener('keydown', (event) => {
  insert.innerHTML = `
  <div class="key">
      ${event.key === ' ' ? 'Space' : event.key}
      <small>event.key</small>
    </div>

    <div class="key">
      ${event.keyCode}
      <small>event.keyCode</small>
    </div>

    <div class="key">
      ${event.code}
      <small>event.code</small>
    </div>
  `;
})
  • window.addEventListener('keydown', (event) => { ... })๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฐฝ(๋ธŒ๋ผ์šฐ์ €)์˜ ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋ฅผ ๋“ฑ๋กํ•œ๋‹ค. ์ด ๋•Œ, ํ‚ค ๋‹ค์šด ์ด๋ฒคํŠธ์ธ 'keydown' ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค. ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ ์‹คํ–‰๋  ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•œ๋‹ค. ์ด ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋Š” event๋ผ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›์œผ๋ฉฐ, ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.
  • ์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ๋Š” insert.innerHTML = ... ;๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ insert ์š”์†Œ์˜ ๋‚ด๋ถ€ HTML์„ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. ์ฆ‰, ์ƒˆ๋กœ์šด HTML ์ฝ”๋“œ๋ฅผ ์‚ฝ์ž…ํ•œ๋‹ค.
  • HTML ์ฝ”๋“œ ๋‚ด๋ถ€์—๋Š” ์„ธ ๊ฐœ์˜
    ์š”์†Œ๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฉฐ, ํด๋ž˜์Šค๊ฐ€ 'key'์ธ ์š”์†Œ๋‹ค. ์ด ์š”์†Œ๋“ค์€ ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ div์š”์†Œ๋Š” ${event.key === ' ' ? 'Space' : event.key}๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ์˜ ํ‚ค๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. ๊ณต๋ฐฑ ํ‚ค๋Š” 'Space'๋กœ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค. small์š”์†Œ์—๋Š” 'event.key'๋ผ๋Š” ํ…์ŠคํŠธ๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
  • ๋‘ ๋ฒˆ์งธ div ์š”์†Œ๋Š” ${event.keyCode}๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ์˜ keyCode๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. small์š”์†Œ์—๋Š” 'event.keyCode'๋ผ๋Š” ํ…์ŠคํŠธ๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
  • ์„ธ ๋ฒˆ์งธ div ์š”์†Œ๋Š” ${event.code}๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ‚ค๋ณด๋“œ ์ด๋ฒคํŠธ์˜ code๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. small์š”์†Œ์—๋Š” 'event.code'๋ผ๋Š” ํ…์ŠคํŠธ๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
profile
์ •์‹ ์ฐจ๋ ค ์ด ๊ฐ๋ฐ•ํ•œ ์„ธ์ƒ์†์—์„œ

0๊ฐœ์˜ ๋Œ“๊ธ€