キーボードの値を取得 - Javascript

  • 作成日:
  • 最終更新日:2025/06/25

キーボードの値を取得する

キーボードの値を取得するには、次のようにします。

index.js

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <title>sample</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>

script.js

window.addEventListener("keydown", (e)=>{
  const key = e.key;
  const code  = e.code;

  console.log("key:" + key);
  console.log("code:" + code);


  // 値は boolean
  const onShift = e.shiftKey;
  const onCtrl  = e.ctrlKey;
  const onAlt   = e.altKey;
  const onMeta  = e.metaKey;

  console.log(onShift);
  console.log(onCtrl);
  console.log(onAlt);
  console.log(onMeta);
});