「jQuery」event.keyでキーコードを判定するサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.0

構文
1.Enterキーのキーコードを判定
event.key === “Enter"
2.Altキーのキーコードを判定
event.key === “Alt"
3.Shiftキーのキーコードを判定
event.key === “Shift"

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#name").keydown(function(event) {
if (event.key === "Shift"){
console.log("shiftキーが押されました");
}
if (event.key === "Control"){
console.log("ctrlキーが押されました");
}
if (event.key === "Enter"){
console.log("Enterキーが押されました");
}
if (event.key === "Alt"){
console.log("altキーが押されました");
}
});
});
</script>
</head>
<body>
<input id="name" type="text" value="" maxlength="1" autocomplete="off">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#name").keydown(function(event) { if (event.key === "Shift"){ console.log("shiftキーが押されました"); } if (event.key === "Control"){ console.log("ctrlキーが押されました"); } if (event.key === "Enter"){ console.log("Enterキーが押されました"); } if (event.key === "Alt"){ console.log("altキーが押されました"); } }); }); </script> </head> <body> <input id="name" type="text" value="" maxlength="1" autocomplete="off"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#name").keydown(function(event) {
      if (event.key === "Shift"){
            console.log("shiftキーが押されました");
      }
      if (event.key === "Control"){
            console.log("ctrlキーが押されました");
      }
    if (event.key === "Enter"){
            console.log("Enterキーが押されました");
      }
      if (event.key === "Alt"){
            console.log("altキーが押されました");
      }
});
});
</script>
</head>
<body>

<input id="name" type="text" value="" maxlength="1" autocomplete="off">

</body>
</html>

実行結果
テキストボックスにエンターキー、アルトキー、シフトキー、コントロールキーを入力するとそれに対応した文字が表示されます。

jQuery

Posted by arkgame