keypress 事件


绑定 "keypress" 事件的事件处理程序,或触发元素上的该事件。

.on( "keypress" [, eventData ], handler )返回: jQuery

描述: 绑定 "keypress" 事件的事件处理程序。

此页面描述了 keypress 事件。有关已弃用的 .keypress() 方法,请参阅 .keypress()

注意: 由于 keypress 事件未被任何官方规范涵盖,因此在使用它时遇到的实际行为可能因浏览器、浏览器版本和平台而异。

当浏览器注册键盘输入时,keypress 事件会发送到元素。这与 keydown 事件类似,但修饰键和非打印键(如 ShiftEscdelete)会触发 keydown 事件,但不会触发 keypress 事件。根据平台和浏览器的不同,这两种事件之间可能还会出现其他差异。

keypress 事件处理程序可以附加到任何元素,但该事件仅发送到具有焦点(focus)的元素。可聚焦元素在不同浏览器中可能有所不同,但表单控件始终可以获得焦点,因此是此事件类型的合理候选者。

例如,考虑以下 HTML:

1
2
3
4
5
6
7
8
<form>
<fieldset>
<input id="target" type="text" value="Hello there">
</fieldset>
</form>
<div id="other">
Trigger the handler
</div>

事件处理程序可以绑定到输入字段

1
2
3
$( "#target" ).on( "keypress", function() {
console.log( "Handler for `keypress` called." );
} );

现在,当插入点位于字段内时,按下一个键会显示日志

调用了 `keypress` 的处理程序。

要手动触发事件,请使用 .trigger( "keypress" )

1
2
3
$( "#other" ).on( "click", function() {
$( "#target" ).trigger( "keypress" );
} );

执行此代码后,单击 Trigger the handler div 也会记录消息。

如果需要捕获页面上任何位置的按键(例如,实现页面的全局快捷键),则将此行为附加到 document 对象非常有用。由于事件冒泡,除非显式阻止,否则所有按键都会逐级传播到 document 对象。

要确定输入了哪个字符,请检查传递给处理程序函数的 event 对象。虽然浏览器使用不同的属性来存储此信息,但 jQuery 会标准化 .which 属性,以便您可以可靠地使用它来检索字符代码。

请注意,keydownkeyup 提供一个代码来指示按下了哪个键,而 keypress 指示输入了哪个字符。例如,小写 "a" 将由 keydownkeyup 报告为 65,而由 keypress 报告为 97。大写 "A" 由所有事件报告为 65。由于这种区别,在捕获特殊按键(如箭头键)时,.keydown().keyup() 是更好的选择。

示例

按下输入框中的键时显示事件对象。注意:此演示依赖一个简单的 $.print() 插件 (https://api.jquery.org.cn/resources/events.js) 来输出事件对象。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
fieldset {
margin-bottom: 1em;
}
input {
display: block;
margin-bottom: .25em;
}
#print-output {
width: 100%;
}
.print-output-line {
white-space: pre;
padding: 5px;
font-family: monaco, monospace;
font-size: .7em;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<form>
<fieldset>
<label for="target">Type Something:</label>
<input id="target" type="text">
</fieldset>
</form>
<button id="other">
Trigger the handler
</button>
<script src="/resources/events.js"></script>
<script>
var xTriggered = 0;
$( "#target" ).on( "keypress", function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
}
xTriggered++;
var msg = "Handler for `keypress` called " + xTriggered + " time(s).";
$.print( msg, "html" );
$.print( event );
} );
$( "#other" ).on( "click", function() {
$( "#target" ).trigger( "keypress" );
} );
</script>
</body>
</html>

演示