3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptによるキーイベント受け取りのテストコード

Posted at

備忘録

参考元: JavaScriptでキーイベントを受け取る方法を現役エンジニアが解説【初心者向け】

参考元のコードを実行すると、ShiftキーやCtrlキーのみを押したとき「keydown: Shift + Shift」「keydown: Ctrl + Control」と出て、少しモヤモヤする。
table3.PNG

そこで、ShiftキーやCtrlキーのみを押したときのコンソール出力を変更する。

<!DOCTYPE html>
<html>
  <head>
    <script>
      document.addEventListener('keydown', (event) => {
         var keyName = event.key;
 
         if (event.ctrlKey) {
            //  処理を変更
             if(keyName === "Control"){
                console.log(`keydown:Ctrl`);
             }else{
                console.log(`keydown:Ctrl + ${keyName}`);
             }
         } else if (event.shiftKey) {
            //  処理を変更
            if(keyName === "Shift"){
                console.log(`keydown:Shift`);
             }else{
                console.log(`keydown:Shift + ${keyName}`);
             }
         } else {
           console.log(`keydown:${keyName}`);
         }
       });
 
       document.addEventListener('keypress', (event) => {
         var keyName = event.key;
 
         if (event.ctrlKey) {
           console.log(`keypress:Ctrl + ${keyName}`);
         } else if (event.shiftKey) {
           console.log(`keypress:Shift + ${keyName}`);
         } else {
           console.log(`keypress:${keyName}`);
         }
       });
    </script>
  </head>
  <body>
  </body>
</html>

実行結果

table4.PNG

これで少しすっきり。ShiftもしくはCtrlキーのみを押された時の挙動が分かりやすくなった。

3
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?