jquery keydownとkeypressとkeyupが実行される順番

jqueryで、keydownとkeypressとkeyupが実行される順番を取得するサンプルコードを記述してます。「mousedown」メソッドを使用してます。
環境
- OS windows10 pro 64bit
- jquery 3.6.0
- Apache 2.4.43
- ブラウザ chrome 91.0.4472.77
keydownとkeypressとkeyupが実行される順番
各イベントは、以下のタイミングで発生します。
keydown | キーが押し込まれた際に発生 |
---|---|
keyup | 押し込まれたキーが上がった 際に発生 |
keypress | キーボードのキーが押された 際に発生 |
以下は、実際にイベントが実行されるタイミングを確認するためのサンプルコードとなります。
※デザインは「semantic-ui」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- semantic.css -->
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
body>.grid {
height: 100%;
}
.fields {
margin-top: 5px;
}
</style>
<script>
$(function () {
$('#txt').on('keydown', function () {
console.log('keydownが実行されました');
});
$('#txt').on('keypress', function () {
console.log('keypressが実行されました');
});
$('#txt').on('keyup', function () {
console.log('keyupが実行されました');
});
})
</script>
<body>
<div class="ui middle aligned center aligned grid">
<div class="column">
<h2 id="result"></h2>
<form class="ui fluid form">
<div class="inline field">
<input id="txt" type="text">
</div>
</form>
</div>
</div>
</body>
</html>
keydown、keypress、keyupの順番で実行されていることが確認できます。

また「shift」キーや「ctrl」キーなど、入力のないキーを押すと「keypress」は実行されません。

以下のようにアロー関数を使用して記述することも可能です。
※アロー関数を使用するとthisの挙動が異なります。
$(() => {
$('#txt').on('keydown', () => {
console.log('keydownが実行されました');
});
$('#txt').on('keypress', () => {
console.log('keypressが実行されました');
});
$('#txt').on('keyup', () => {
console.log('keyupが実行されました');
});
})
-
前の記事
javascript エラー「ReferenceError: Can’t find variable: xxx」の解決方法 2022.05.06
-
次の記事
Ruby redisに接続してキーの値を取得する 2022.05.06
コメントを書く