--- title: KeyboardEvent slug: Web/API/KeyboardEvent tags: - API - DOM - Event - JavaScript - KeyboardEvent - 事件 - 接口 - 键盘 - 键盘事件 translation_of: Web/API/KeyboardEvent ---
{{APIRef("DOM Events")}}
KeyboardEvent
对象描述了用户与键盘的交互。 每个事件都描述了用户与一个按键(或一个按键和修饰键的组合)的单个交互;事件类型keydown
, keypress
与 keyup
用于识别不同的键盘活动类型。
KeyboardEvent
只在低级别提示用户与一个键盘按键的交互是什么,不涉及这个交互的上下文含义。 当你需要处理文本输入的时候,使用 {{event("input")}} 事件代替。用户使用其他方式输入文本时,如使用平板电脑的手写系统或绘图板, 键盘事件可能不会触发。KeyboardEvent
对象。KeyboardEvent
接口定义了以下常量。
下述常量用于识别产生按键事件的键盘位置,以类似 KeyboardEvent.DOM_KEY_LOCATION_STANDARD
的形式来访问。
常量 | 值 | 描述 |
---|---|---|
DOM_KEY_LOCATION_STANDARD |
0x00 |
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. Examples include alphanumeric keys on the standard PC 101 US keyboard, the NumLock key, and the space bar. |
DOM_KEY_LOCATION_LEFT |
0x01 |
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. Examples include the left Control key, the left Command key on a Macintosh keyboard, or the left Shift key. |
DOM_KEY_LOCATION_RIGHT |
0x02 |
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. Examples include the right Shift key and the right Alt key (Option on a Mac keyboard). |
DOM_KEY_LOCATION_NUMPAD |
0x03 |
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 Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad. |
此接口从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 中继承属性。
true
。true
。true
if the event is fired between after compositionstart
and before compositionend
.true
if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞)) was active when the key event was generated.true
if the key is being held down such that it is automatically repeating.true
if the Shift key was active when the key event was generated.此接口从 {{domxref("UIEvent")}} 和 {{domxref("Event")}} 中继承方法。
KeyboardEvent
object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.KeyboardEvent
object. This is now deprecated. You should instead use the {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor.keypress
event. For keys whose char
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.
keyCode
.
The following events are based on the KeyboardEvent
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 Document
handler for the event, which applies generally to all of the recipients.
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:
keydown
event is sent.keypress
event is sent.keyup
event is sent.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 keydown
and keyup
events.
On Linux, Firefox 12 and earlier also dispatched the keypress
event for these keys.
However, a limitation of the macOS event model causes Caps Lock to dispatch only the keydown
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 keypress
event; this inconsistent behavior was {{bug(602812)}}.
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:
keydown
keypress
keydown
keypress
keyup
This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.
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:
keydown
keypress
keyup
keydown
keypress
keyup
keyup
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.
Before Gecko 5.0 {{geckoRelease('5.0')}}, keyboard handling was less consistent across platforms.
Note: Manually firing an event does not 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.
<!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>
规范 | 状态 | 注释 |
---|---|---|
{{SpecName('UI Events', '#interface-keyboardevent', 'KeyboardEvent')}} | {{Spec2('UI Events')}} |
The KeyboardEvent
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()")}}.
{{Compat("api.KeyboardEvent")}}
keypress
event is no longer fired for non-printable keys ({{bug(968056)}}), except for the Enter key, and the Shift + Enter and Ctrl + Enter key combinations (these were kept for cross-browser compatibility purposes).