Code/JavaScript

[Javascript] 키보드 입력 키값

codens 2022. 5. 1. 13:37


    - 자바스크립트 keyboard event key value

KeyboardEvent
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

예제

document.addEventListener("keydown", (event) => {
            const keyName = event.key;
            if (keyName === "Control") {
                console.log(`Ctrl 키 눌림`);
                return;
            }

            if (event.ctrlKey) {
                // Ctrl 키와 다른 키의 조합
                console.log(`Ctrl 키 + ${keyName}`);
            } else {
                console.log(`키 = ${keyName}`);
            }
        },
        false
    );

    document.addEventListener("keyup", (event) => {
            const keyName = event.key;

            if (keyName === "Control") {
                console.log("Ctrl 키 해제");
            }
        },
        false
    );


//-------------------------------------
* 보조키 눌렸는지 여부 판정
altKey - 좌
ctrlKey - 좌
shiftKey - 좌, 우 


//-------------------------------------
* KeyboardEvent.code
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

    - 코드값
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values
        - 멀티미디어 키값 없음


//-------------------------------------
* KeyboardEvent.key
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

    - 키값
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

    - 멀티미디어 키값 있음
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values#multimedia_keys
MediaStop  , MediaPlayPause  , MediaTrackPrevious  , MediaTrackNext 
AudioVolumeMute , AudioVolumeDown , AudioVolumeUp 

//

  KeyboardEvent
  code key
  ControlLeft Control
  ControlRight HanjaMode
  AltLeft Alt
  AltRight HangulMode
  ShiftLeft Shift
  ShiftRight Shift
  Enter Enter
  NumpadEnter Enter
  Digit1 1
  KeyA a
  Tab Tab
  F1 F1
  Escape Escape
  Backslash \
  Slash /
  Numpad0 Insert or 0
멀티미디어 키 없음 MediaStop  , MediaPlayPause  , MediaTrackPrevious  , MediaTrackNext
  없음 AudioVolumeMute , AudioVolumeDown , AudioVolumeUp

 

//



//-------------------------------------
* 삭제 예정 (Deprecated)
keypress 이벤트

KeyboardEvent.keyCode
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

KeyboardEvent.charCode - 모두 0


//-----------------------------------------------------------------------------
< 참고 >
JavaScript Keycode List – Keypress Event Key Codes for Enter, Space, Backspace, and More
https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/

반응형