jquery ctrlキーやshiftキーとの他のキー同時押しを取得する
- 2020.08.23
- jquery

jqueryでctrlキーやshiftキーとの他のキー同時押しが発生した場合のイベントを取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
サンプルコード
各キーをkeydownイベントを取得後、キーコードにより処理を分岐させてます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <style> .container { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> $(document).ready(function(){ $(window).keydown(function(e){ // ctrl + key if(event.ctrlKey){ if(e.keyCode === 67){ $(".alert-success").text('ctrl+c'); } else if(e.keyCode === 86){ $(".alert-success").text('ctrl+v'); } return false; } // shift + key if(event.shiftKey){ if(e.keyCode === 81){ $(".alert-success").text('shift+q'); } else if(e.keyCode === 90){ $(".alert-success").text('shift+z'); } return false; } // alt + key if(event.altKey){ if(e.keyCode === 67){ $(".alert-success").text('alt+c'); } else if(e.keyCode === 86){ $(".alert-success").text('alt+v'); } return false; } }); }); </script> <body> <div class="container"> <div class="alert alert-success" role="alert"> 押下されたキー </div> </div> </body> </html> |
実行結果を見ると、同時押しが取得できていることが確認できます。

-
前の記事
Nuxt.js ライブラリ「vue-typeahead-bootstrap」をインストールしてオートコンプリートを実装する 2020.08.23
-
次の記事
javascript 選択中のテキストを取得する 2020.08.23
コメントを書く