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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
---
title: KeyboardEvent
slug: Web/API/KeyboardEvent
tags:
- API
- DOM
- Event
- JavaScript
- KeyboardEvent
- 事件
- 接口
- 键盘
- 键盘事件
translation_of: Web/API/KeyboardEvent
---
<p>{{APIRef("DOM Events")}}</p>
<p><strong><code>KeyboardEvent</code></strong> 对象描述了用户与键盘的交互。 每个事件都描述了用户与一个按键(或一个按键和修饰键的组合)的单个交互;事件类型<code>keydown</code>, <code>keypress</code> 与 <code>keyup</code> 用于识别不同的键盘活动类型。</p>
<div class="note"> <strong>注意:</strong><code>KeyboardEvent</code> 只在低级别提示用户与一个键盘按键的交互是什么,不涉及这个交互的上下文含义。 当你需要处理文本输入的时候,使用 {{event("input")}} 事件代替。用户使用其他方式输入文本时,如使用平板电脑的手写系统或绘图板, 键盘事件可能不会触发。</div>
<h2 id="构造函数">构造函数</h2>
<dl>
<dt>{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}</dt>
<dd>创建一个 <code>KeyboardEvent</code> 对象。</dd>
</dl>
<h2 id="常量">常量</h2>
<p><code>KeyboardEvent</code> 接口定义了以下常量。</p>
<h3 id="键盘定位">键盘定位</h3>
<p>下述常量用于识别产生按键事件的键盘位置,以类似 <code>KeyboardEvent.DOM_KEY_LOCATION_STANDARD</code> 的形式来访问。</p>
<table class="standard-table">
<caption>键盘定位标识符</caption>
<thead>
<tr>
<th scope="col">常量</th>
<th scope="col">值</th>
<th scope="col">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>DOM_KEY_LOCATION_STANDARD</code></td>
<td>0x00</td>
<td>
<p>The key described by the event is not identified as being located in a particular area of the keyboard; it is not located on the numeric keypad (unless it's the NumLock key), and for keys that are duplicated on the left and right sides of the keyboard, the key is, for whatever reason, not to be associated with that location.</p>
<p>Examples include alphanumeric keys on the standard PC 101 US keyboard, the NumLock key, and the space bar.</p>
</td>
</tr>
<tr>
<td><code>DOM_KEY_LOCATION_LEFT</code></td>
<td>0x01</td>
<td>
<p>The key is one which may exist in multiple locations on the keyboard and, in this instance, is on the left side of the keyboard.</p>
<p>Examples include the left Control key, the left Command key on a Macintosh keyboard, or the left Shift key.</p>
</td>
</tr>
<tr>
<td><code>DOM_KEY_LOCATION_RIGHT</code></td>
<td>0x02</td>
<td>
<p>The key is one which may exist in multiple positions on the keyboard and, in this case, is located on the right side of the keyboard.</p>
<p>Examples include the right Shift key and the right Alt key (Option on a Mac keyboard).</p>
</td>
</tr>
<tr>
<td><code>DOM_KEY_LOCATION_NUMPAD</code></td>
<td>0x03</td>
<td>
<p>The key is located on the numeric keypad, or is a virtual key associated with the numeric keypad if there's more than one place the key could originate from. The NumLock key does not fall into this group and is always encoded with the location <code>DOM_KEY_LOCATION_STANDARD</code>.</p>
<p>Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad.</p>
</td>
</tr>
</tbody>
</table>
<dl>
</dl>
<h2 id="属性">属性</h2>
<p><em>此接口从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 中继承属性。</em></p>
<dl>
<dt>{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}</dt>
<dd>返回一个 {{jsxref("Boolean")}},如果按键事件产生时, <kbd>Alt</kbd> (OS X 中是 <kbd>Option</kbd> 或 <kbd>⌥</kbd> )键被按下,则该值为 <code>true</code> 。</dd>
<dt>{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}</dt>
<dd>返回一个 {{domxref("DOMString")}},其code值代表触发事件的物理按键。
<div class="warning"><strong>警告:</strong>这个属性会忽略用户的键盘布局,所以如果用户在QWERTY布局的键盘上按下“Y”位置(第一行字母按键的中间)的按键时,这个属性会返回“KeyY”,即使用户使用QWERTZ布局的键盘(此时用户输入的就是“Z”,其他属性也会提示“Z”)或Dvorak键盘(此时用户输入的就是“F”)也是如此。</div>
</dd>
<dt>{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}</dt>
<dd>返回一个 {{jsxref("Boolean")}},如果按键事件发生时 <kbd>Ctrl</kbd> 键被按下,则该值为 <code>true</code> 。</dd>
<dt>{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the event is fired between after <code>compositionstart</code> and before <code>compositionend</code>.</dd>
<dt>{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}</dt>
<dd>Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.</dd>
<dt>{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}</dt>
<dd>Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.
<div class="note"><strong>Note:</strong> This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.</div>
</dd>
<dt>{{domxref("KeyboardEvent.location")}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Number")}} representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown above in {{anch("Keyboard locations")}}.</dd>
<dt>{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the <kbd>Meta</kbd> key (on Mac keyboards, the <kbd>⌘ Command</kbd> key; on Windows keyboards, the Windows key (<kbd>⊞</kbd>)) was active when the key event was generated.</dd>
<dt>{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the key is being held down such that it is automatically repeating.</dd>
<dt>{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> if the <kbd>Shift</kbd> key was active when the key event was generated.</dd>
</dl>
<h2 id="方法">方法</h2>
<p><em>此接口从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 中继承方法。</em></p>
<dl>
<dt>{{domxref("KeyboardEvent.getModifierState()")}}</dt>
<dd>Returns a {{jsxref("Boolean")}} indicating if a modifier key such as <kbd>Alt</kbd>, <kbd>Shift</kbd>, <kbd>Ctrl</kbd>, or <kbd>Meta</kbd>, was pressed when the event was created.</dd>
</dl>
<h2 id="过时方法">过时方法</h2>
<dl>
<dt>{{domxref("KeyboardEvent.initKeyEvent()")}} {{deprecated_inline}}</dt>
<dd>Initializes a <code>KeyboardEvent</code> object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.</dd>
<dt>{{domxref("KeyboardEvent.initKeyboardEvent()")}} {{deprecated_inline}}</dt>
<dd>Initializes a <code>KeyboardEvent</code> object. This is now deprecated. You should instead use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.</dd>
</dl>
<h2 id="过时属性">过时属性</h2>
<dl>
<dt>{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}</dt>
<dd>Returns a {{domxref("DOMString")}} representing the character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string.
<div class="note"><strong>Note:</strong> If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.</div>
</dd>
<dt>{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Number")}} representing the Unicode reference number of the key; this attribute is used only by the <code>keypress</code> event. For keys whose <code>char</code> attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters.
<div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.</div>
</dd>
<dt>{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Number")}} representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.
<div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.</div>
</dd>
<dt>{{domxref("KeyboardEvent.keyIdentifier")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}</dt>
<dd>This property is non-standard and has been deprecated in favor of {{domxref("KeyboardEvent.key")}}. It was part of an old version of DOM Level 3 Events.</dd>
<dt>{{domxref("KeyboardEvent.keyLocation")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}</dt>
<dd>This is a non-standard deprecated alias for {{domxref("KeyboardEvent.location")}}. It was part of an old version of DOM Level 3 Events.</dd>
<dt>{{domxref("KeyboardEvent.which")}} {{deprecated_inline}} {{Readonlyinline}}</dt>
<dd>Returns a {{jsxref("Number")}} representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as <code>keyCode</code>.
<div class="warning"><strong>Warning:</strong> This attribute is deprecated; you should use {{domxref("KeyboardEvent.key")}} instead, if available.</div>
</dd>
</dl>
<h2 id="事件">事件</h2>
<p>The following events are based on the <code>KeyboardEvent</code> type. They can be delivered to any object which implements {{domxref("GlobalEventHandlers")}}, including {{domxref("Element")}}, {{domxref("Document")}}, and {{domxref("Window")}}. In the list below, each event links to the documentation for the <code>Document</code> handler for the event, which applies generally to all of the recipients.</p>
<dl>
<dt>{{domxref("Document.keydown_event", "keydown")}}</dt>
<dd>A key has been pressed.</dd>
<dt>{{domxref("Document.keyup_event", "keyup")}}</dt>
<dd>A key has been released.</dd>
</dl>
<h3 id="过时事件">过时事件</h3>
<dl>
<dt>{{domxref("Document.keypress_event", "keypress")}} {{obsolete_inline}}</dt>
<dd>通常在一个按键被按下时触发,并产生一个字符串值,这个事件高度依赖硬件(highly device-dependent )且废弃,您不应该使用它</dd>
</dl>
<h2 id="用法说明">用法说明</h2>
<p>There are three types of keyboard events: {{event("keydown")}}, {{event("keypress")}}, and {{event("keyup")}}. For most keys, Gecko dispatches a sequence of key events like this:</p>
<ol>
<li>When the key is first pressed, the <code>keydown</code> event is sent.</li>
<li>If the key is not a modifier key, the <code>keypress</code> event is sent.</li>
<li>When the user releases the key, the <code>keyup</code> event is sent.</li>
</ol>
<h3 id="特殊情况">特殊情况</h3>
<p>Some keys toggle the state of an indicator light; these include keys such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the <code>keydown</code> and <code>keyup</code> events.</p>
<div class="note">
<p>On Linux, Firefox 12 and earlier also dispatched the <code>keypress</code> event for these keys.</p>
</div>
<p>However, a limitation of the macOS event model causes Caps Lock to dispatch only the <code>keydown</code> event. Num Lock was supported on some older laptop models (2007 models and older), but since then, macOS hasn't supported Num Lock even on external keyboards. On older MacBooks with a Num Lock key, that key doesn't generate any key events. Gecko does support the Scroll Lock key if an external keyboard which has an F14 key is connected. In certain older versions of Firefox, this key generated a <code>keypress</code> event; this inconsistent behavior was {{bug(602812)}}.</p>
<h3 id="Auto-repeat_handling">Auto-repeat handling</h3>
<p>When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:</p>
<ol>
<li><code>keydown</code></li>
<li><code>keypress</code></li>
<li><code>keydown</code></li>
<li><code>keypress</code></li>
<li><<repeating until the user releases the key>></li>
<li><code>keyup</code></li>
</ol>
<p>This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.</p>
<h4 id="Auto-repeat_on_some_GTK_environments_such_as_Ubuntu_9.4">Auto-repeat on some GTK environments such as Ubuntu 9.4</h4>
<p>In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:</p>
<ol>
<li><code>keydown</code></li>
<li><code>keypress</code></li>
<li><code>keyup</code></li>
<li><code>keydown</code></li>
<li><code>keypress</code></li>
<li><code>keyup</code></li>
<li><<repeating until the user releases the key>></li>
<li><code>keyup</code></li>
</ol>
<p>In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.</p>
<h4 id="Auto-repeat_handling_prior_to_Gecko_5.0">Auto-repeat handling prior to Gecko 5.0</h4>
<p>Before Gecko 5.0 {{geckoRelease('5.0')}}, keyboard handling was less consistent across platforms.</p>
<dl>
<dt>Windows</dt>
<dd>Auto-repeat behavior is the same as in Gecko 4.0 and later.</dd>
<dt>Mac</dt>
<dd>After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.</dd>
<dt>Linux</dt>
<dd>The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.</dd>
</dl>
<p class="note"><strong>Note:</strong> Manually firing an event does <em>not</em> generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.</p>
<h2 id="示例">示例</h2>
<pre class="brush: js notranslate"><!DOCTYPE html>
<html>
<head>
<script>
'use strict';
document.addEventListener('keydown', (event) => {
const keyName = event.key;
if (keyName === 'Control') {
// do not alert when only Control key is pressed.
return;
}
if (event.ctrlKey) {
// Even though event.key is not 'Control' (e.g., 'a' is pressed),
// event.ctrlKey may be true if Ctrl key is pressed at the same time.
alert(`Combination of ctrlKey + ${keyName}`);
} else {
alert(`Key pressed ${keyName}`);
}
}, false);
document.addEventListener('keyup', (event) => {
const keyName = event.key;
// As the user releases the Ctrl key, the key is no longer active,
// so event.ctrlKey is false.
if (keyName === 'Control') {
alert('Control key was released');
}
}, false);
</script>
</head>
<body>
</body>
</html>
</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">注释</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('UI Events', '#interface-keyboardevent', 'KeyboardEvent')}}</td>
<td>{{Spec2('UI Events')}}</td>
<td></td>
</tr>
</tbody>
</table>
<p>The <code>KeyboardEvent</code> interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.</p>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("api.KeyboardEvent")}}</p>
<h3 id="兼容性说明">兼容性说明</h3>
<ul>
<li>As of Firefox 65, the <code>keypress</code> event is no longer fired for <a href="/en-US/docs/Web/API/KeyboardEvent/keyCode#Non-printable_keys_(function_keys)">non-printable keys</a> ({{bug(968056)}}), except for the <kbd>Enter</kbd> key, and the <kbd>Shift</kbd> + <kbd>Enter</kbd> and <kbd>Ctrl</kbd> + <kbd>Enter</kbd> key combinations (these were kept for cross-browser compatibility purposes).</li>
</ul>
<h2 id="参见">参见</h2>
<ul>
<li>{{domxref("KeyboardEvent.code")}}.</li>
<li>{{domxref("KeyboardEvent.key")}}.</li>
<li>{{domxref("KeyboardEvent.getModifierState()")}}</li>
</ul>
|