본문 바로가기
Coding/JavaScript

[JavaScript] 자바스크립트로 가상키보드 구현하는 방법 !!

by 포스트it 2023. 3. 12.
728x90
반응형

 

[JavaScript] 자바스크립트로 가상키보드 구현하는 방법 !!

simple-keyboard 라는 라이브러리 사용하였습니다 ㅎ

한글버전은 없어 따로 구현해야 한다고 하네요.

 

출처.

hodgef/simple-keyboard: Javascript Virtual Keyboard - Customizable, responsive and lightweight (github.com)

 

GitHub - hodgef/simple-keyboard: Javascript Virtual Keyboard - Customizable, responsive and lightweight

Javascript Virtual Keyboard - Customizable, responsive and lightweight - GitHub - hodgef/simple-keyboard: Javascript Virtual Keyboard - Customizable, responsive and lightweight

github.com

 

예시코드
<html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/simple-keyboard@latest/build/css/index.css">
</head>

<body>
  <input class="input" placeholder="Tap on the virtual keyboard to start" />
  <div class="simple-keyboard"></div>

  <script src="https://cdn.jsdelivr.net/npm/simple-keyboard@latest/build/index.js"></script>
</body>
</html>
<script>
let Keyboard = window.SimpleKeyboard.default;

let keyboard = new Keyboard({
  onChange: input => onChange(input),
  onKeyPress: button => onKeyPress(button)
});

/**
 * Update simple-keyboard when input is changed directly
 */
document.querySelector(".input").addEventListener("input", event => {
  keyboard.setInput(event.target.value);
});

console.log(keyboard);

function onChange(input) {
  document.querySelector(".input").value = input;
  console.log("Input changed", input);
}

function onKeyPress(button) {
  console.log("Button pressed", button);

  /**
   * If you want to handle the shift and caps lock buttons
   */
  if (button === "{shift}" || button === "{lock}") handleShift();
}

function handleShift() {
  let currentLayout = keyboard.options.layoutName;
  let shiftToggle = currentLayout === "default" ? "shift" : "default";

  keyboard.setOptions({
    layoutName: shiftToggle
  });
}

</script>

결과값

 

728x90
반응형

댓글