KeyboardEvent

KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ( keydown , keypress ,或 keyup ) identifies what kind of keyboard activity occurred.

注意: KeyboardEvent events just indicate what interaction the user had with a key on the keyboard at a low level, providing no contextual meaning to that interaction. When you need to handle text input, use the input event instead. Keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet.

构造函数

KeyboardEvent()
创建新的 KeyboardEvent 对象。

常量

KeyboardEvent interface defines the following constants.

Keyboard locations

The following constants identify which part of the keyboard the key event originates from. They are accessed as KeyboardEvent.DOM_KEY_LOCATION_STANDARD and so forth.

Keyboard location identifiers
常量 描述
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 DOM_KEY_LOCATION_STANDARD .

Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad.

特性

This interface also inherits properties of its parents, UIEvent and Event .

KeyboardEvent.altKey 只读
返回 Boolean that is true Alt ( Option or on OS X) key was active when the key event was generated.
KeyboardEvent.code 只读
返回 DOMString with the code value of the physical key represented by the event.
警告: This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F").
KeyboardEvent.ctrlKey 只读
返回 Boolean that is true Ctrl key was active when the key event was generated.
KeyboardEvent.isComposing 只读
返回 Boolean that is true if the event is fired between after compositionstart and before compositionend .
KeyboardEvent.key 只读
返回 DOMString representing the key value of the key represented by the event.
KeyboardEvent.locale 只读
返回 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.
注意: 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.
KeyboardEvent.location 只读
返回 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 Keyboard locations .
KeyboardEvent.metaKey 只读
返回 Boolean that is true Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key ( )) was active when the key event was generated.
KeyboardEvent.repeat 只读
返回 Boolean that is true if the key is being held down such that it is automatically repeating.
KeyboardEvent.shiftKey 只读
返回 Boolean that is true Shift key was active when the key event was generated.

方法

This interface also inherits methods of its parents, UIEvent and Event .

KeyboardEvent.getModifierState()
返回 Boolean indicating if a modifier key such as Alt , Shift , Ctrl ,或 Meta , was pressed when the event was created.

Obsolete methods

KeyboardEvent.initKeyEvent()
Initializes a KeyboardEvent object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the KeyboardEvent() 构造函数。
KeyboardEvent.initKeyboardEvent()
Initializes a KeyboardEvent object. This is now deprecated. You should instead use the KeyboardEvent() 构造函数。

过时特性

KeyboardEvent.char 只读
返回 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.
注意: 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.
KeyboardEvent.charCode 只读
返回 Number representing the Unicode reference number of the key; this attribute is used only by the 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.
警告: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.
KeyboardEvent.keyCode 只读
返回 Number representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.
警告: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.
KeyboardEvent.keyIdentifier 只读
This property is non-standard and has been deprecated in favor of KeyboardEvent.key . It was part of an old version of DOM Level 3 Events.
KeyboardEvent.keyLocation 只读
This is a non-standard deprecated alias for KeyboardEvent.location . It was part of an old version of DOM Level 3 Events.
KeyboardEvent.which 只读
返回 Number representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode .
警告: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.

Events

The following events are based on the KeyboardEvent type. They can be delivered to any object which implements GlobalEventHandlers ,包括 Element , Document ,和 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.

keydown
A key has been pressed.
keyup
A key has been released.

Obsolete events

keypress
A key that normally produces a character value has been pressed. This event was highly device-dependent and is obsolete. You should not use it.

Usage notes

There are three types of keyboard events: keydown , keypress ,和 keyup . For most keys, Gecko dispatches a sequence of key events like this:

  1. When the key is first pressed, the keydown event is sent.
  2. If the key is not a modifier key, the keypress event is sent.
  3. When the user releases the key, the keyup event is sent.

Special cases

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 事件。

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 .

Auto-repeat handling

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:

  1. keydown
  2. keypress
  3. keydown
  4. keypress
  5. <<repeating until the user releases the key>>
  6. keyup

This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

Auto-repeat on some GTK environments such as Ubuntu 9.4

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:

  1. keydown
  2. keypress
  3. keyup
  4. keydown
  5. keypress
  6. keyup
  7. <<repeating until the user releases the key>>
  8. 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.

Auto-repeat handling prior to Gecko 5.0

Before Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), keyboard handling was less consistent across platforms.

Windows
Auto-repeat behavior is the same as in Gecko 4.0 and later.
Mac
After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
Linux
The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.

注意: 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>
					

规范

规范 状态 Comment
UI Events
The definition of 'KeyboardEvent' in that specification.
工作草案

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, KeyboardEvent.initKeyEvent() by Gecko browsers and the early DOM Events Level 3 version, KeyboardEvent.initKeyboardEvent() by others. Both have been superseded by the modern usage of a constructor: KeyboardEvent() .

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
KeyboardEvent Chrome 1 Edge 12 Firefox 1.5 IE 9 Opera 12.1 Safari 3.1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 12.1 Safari iOS 2 Samsung Internet Android 1.0
DOM_KEY_LOCATION_LEFT Chrome Yes Edge ≤18 Firefox Yes IE ? Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
DOM_KEY_LOCATION_NUMPAD Chrome Yes Edge ≤18 Firefox Yes IE ? Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
DOM_KEY_LOCATION_RIGHT Chrome Yes Edge ≤18 Firefox Yes IE ? Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
DOM_KEY_LOCATION_STANDARD Chrome Yes Edge ≤18 Firefox Yes IE ? Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
KeyboardEvent() 构造函数 Chrome Yes Edge ≤79 Firefox 31 IE No Opera Yes Safari ? WebView Android Yes Chrome Android Yes Firefox Android 31 Opera Android Yes Safari iOS ? Samsung Internet Android Yes
altKey Chrome Yes Edge 12 Firefox Yes IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
charCode
弃用 非标
Chrome 26 Edge 12 Firefox 3 IE 9 Opera 12.1 Safari 5.1 WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS 5.1 Samsung Internet Android Yes
code Chrome 48 Edge 79 Firefox 38 IE No Opera 35 Safari 10 WebView Android 48 Chrome Android 48 Firefox Android 38 Opera Android 35 Safari iOS 10 Samsung Internet Android 5.0
ctrlKey Chrome Yes Edge 12 Firefox Yes IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
getModifierState Chrome 31 Edge 12 Firefox 15 IE 9 Opera 17 Safari 10.1 WebView Android 4.4.3 Chrome Android 31 Firefox Android 15 Opera Android 18 Safari iOS 10.3 Samsung Internet Android 2.0
isComposing Chrome 56 Edge ≤79 Firefox 31 IE No Opera 43 Safari 10.1 WebView Android 56 Chrome Android 56 Firefox Android 31 Opera Android 43 Safari iOS 10.3 Samsung Internet Android 6.0
key Chrome 51 Edge 12 Firefox 23 IE 9
9
IE's implementation does not completely match the current spec because it is based on an older version of the spec.
Opera 38 Safari 10 WebView Android 51 Chrome Android 51 Firefox Android 23 Opera Android 41 Safari iOS 10 Samsung Internet Android 5.0
keyCode
弃用 非标
Chrome 26 Edge 12 Firefox 3 IE 9 Opera 12.1 Safari 5 WebView Android ≤37 Chrome Android 26 Firefox Android 4 Opera Android 12.1 Safari iOS 5.1 Samsung Internet Android 1.5
keyIdentifier
弃用 非标
Chrome 26 — 54 Edge ? Firefox No IE No Opera 15 — 41 Safari 5.1 WebView Android ? — 54 Chrome Android 26 — 54 Firefox Android No Opera Android ? — 41 Safari iOS 5.1 Samsung Internet Android 1.5 — 6.0
location Chrome Yes Edge 12 Firefox 15 IE 9 Opera Yes Safari 6.1 WebView Android Yes Chrome Android Yes Firefox Android 15 Opera Android Yes Safari iOS 8 Samsung Internet Android Yes
metaKey Chrome Yes Edge 12 Firefox Yes IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
repeat Chrome Yes Edge 79 Firefox 28 IE No Opera Yes Safari 10.1 WebView Android Yes Chrome Android Yes Firefox Android 28 Opera Android Yes Safari iOS 10.3 Samsung Internet Android Yes
shiftKey Chrome Yes Edge 12 Firefox Yes IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
which
弃用 非标
Chrome 4 Edge 12 Firefox 2
2
Firefox also implements this property on the UIEvent 接口。
IE 9 Opera 12.1 Safari 5.1 WebView Android Yes Chrome Android Yes Firefox Android Yes
Yes
Firefox also implements this property on the UIEvent 接口。
Opera Android 12.1 Safari iOS 5.1 Samsung Internet Android Yes

图例

完整支持
完整支持
不支持
不支持
兼容性未知
兼容性未知
非标。预期跨浏览器支持较差。
非标。预期跨浏览器支持较差。
弃用。不要用于新网站。
弃用。不要用于新网站。
见实现注意事项。

Compatibility notes

  • As of Firefox 65, the 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).

另请参阅