9cubed
ブログ | Tailwind | Vite | Python | Node.js | Linux | PowerShell | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

jQuery - submitイベント

次の記事 >

jQuery - mousedownイベント、mouseupイベント、mousemoveイベント、

jQuery

jQuery - keydownイベント、keypressイベント、keyupイベント

公開日:2018-12-21
更新日:2019-05-14

1. 概要

キーが押された時にkeydownイベント、キーが押されている間にkeypressイベント、キーが離された時にkeyupイベントが発生します。
押されたキーは、イベントの引数の e.ctrlKey、e.shiftKey、e.keyCode で取得できます。
event.ctrlKey、event.shiftKey、event.keyCode でも取得できますが、Firefox では動かないため、要注意です。

//キーが押された時
$(セレクタ).on("keydown", function(e) {
	処理;
});

//キーが押されている間
$(セレクタ).on("keypress", function(e) {
	処理;
});

//キーが離された時
$(セレクタ).on("keyup", function(e) {
	処理;
});

2. サンプル

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>jQuery</title><style>body{color:#fff; background-color:#000;}</style></head>
<body>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <input type="text" value="" /><br /><br />

  <div>Control:<span id="msg1"></span></div>
  <div>Shift  :<span id="msg2"></span></div>
  <div>Key    :<span id="msg3"></span></div>

  <script>

    function showKey(isCtrl, isShift, keyCode) {
      $("#msg1").html(isCtrl);
      $("#msg2").html(isShift);
      $("#msg3").html(keyCode);
    }

    $(":text").on("keydown", function(e) {
      showKey(e.ctrlKey, e.shiftKey, e.keyCode);
    });

    $(":text").on("keypress", function(e) {
      showKey(e.ctrlKey, e.shiftKey, e.keyCode);
    });

    $(":text").on("keyup", function(e) {
      showKey(e.ctrlKey, e.shiftKey, e.keyCode);
    });

  </script>
</body></html>

実行結果:画面



< 前の記事

jQuery - submitイベント

次の記事 >

jQuery - mousedownイベント、mouseupイベント、mousemoveイベント、

YouTube X

新着一覧

  • SCSS のインストールVite
  • Tailwind CSS のプロジェクトの作成Tailwind
  • TypeScriptのプロジェクトの作成Vite
  • Flask のインストールと動作確認Python
  • 簡易Webサーバーの作成Python
  • pipeline で文章の生成Python
  • pipeline で文章の要約Python
  • 音声から文字起こしPython
  • Node.js のインストールNode.js
  • .ps1(PowerShellスクリプト)を実行可能にするPowerShell

アーカイブ

  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲