KeyboardEvent

翻译不完整。 请帮助我们翻译这篇文章!

KeyboardEvent 对象描述了用户与键盘的交互。 每个事件都描述了用户与一个按键(或一个按键和修饰键的组合)的单个交互;事件类型keydownkeypresskeyup 用于识别不同的键盘活动类型。

 注意:KeyboardEvent 只在低级别提示用户与一个键盘按键的交互是什么,不涉及这个交互的上下文含义。 当你需要处理文本输入的时候,使用 input 事件代替。用户使用其他方式输入文本时,如使用平板电脑的手写系统或绘图板, 键盘事件可能不会触发。

构造函数

KeyboardEvent()
创建一个 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 DOM_KEY_LOCATION_STANDARD.

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

属性

此接口从 UIEventEvent 中继承属性。

KeyboardEvent.altKey 只读
返回一个 Boolean,如果按键事件产生时, Alt (OS X 中是 Option 或  )键被按下,则该值为 true 。
KeyboardEvent.code 只读
返回一个 DOMString,其code值代表触发事件的物理按键。
警告:这个属性会忽略用户的键盘布局,所以如果用户在QWERTY布局的键盘上按下“Y”位置(第一行字母按键的中间)的按键时,这个属性会返回“KeyY”,即使用户使用QWERTZ布局的键盘(此时用户输入的就是“Z”,其他属性也会提示“Z”)或Dvorak键盘(此时用户输入的就是“F”)也是如此。
KeyboardEvent.ctrlKey 只读
返回一个 Boolean,如果按键事件发生时 Ctrl 键被按下,则该值为 true 。
KeyboardEvent.isComposing 只读
Returns a Boolean that is true if the event is fired between after compositionstart and before compositionend.
KeyboardEvent.key 只读
Returns a DOMString representing the key value of the key represented by the event.
KeyboardEvent.locale 只读
Returns a 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.
Note: 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 只读
Returns a 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 只读
Returns a Boolean that is 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.
KeyboardEvent.repeat 只读
Returns a Boolean that is true if the key is being held down such that it is automatically repeating.
KeyboardEvent.shiftKey 只读
Returns a Boolean that is true if the Shift key was active when the key event was generated.

方法

此接口从 UIEventEvent 中继承方法。

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

过时方法

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() constructor.
KeyboardEvent.initKeyboardEvent()
Initializes a KeyboardEvent object. This is now deprecated. You should instead use the KeyboardEvent() constructor.

过时属性

KeyboardEvent.char 只读
Returns a 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.
Note: 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 只读
Returns a 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.
Warning: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.
KeyboardEvent.keyCode 只读
Returns a Number representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.
Warning: 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 只读
Returns a Number representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode.
Warning: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.

事件

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

过时事件

keypress
通常在一个按键被按下时触发,并产生一个字符串值,这个事件高度依赖硬件(highly device-dependent )且废弃,您不应该使用它

用法说明

There are three types of keyboard events: keydown, keypress, and 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.

特殊情况

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.

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.

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>

规范

规范 状态 注释
UI Events
KeyboardEvent
Working Draft

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, 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().

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
KeyboardEventChrome Full support 1Edge Full support 12Firefox Full support 1.5IE Full support 9Opera Full support 12.1Safari Full support 3.1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 12.1Safari iOS Full support 2Samsung Internet Android Full support 1.0
DOM_KEY_LOCATION_LEFTChrome Full support YesEdge Full support ≤18Firefox Full support YesIE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
DOM_KEY_LOCATION_NUMPADChrome Full support YesEdge Full support ≤18Firefox Full support YesIE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
DOM_KEY_LOCATION_RIGHTChrome Full support YesEdge Full support ≤18Firefox Full support YesIE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
DOM_KEY_LOCATION_STANDARDChrome Full support YesEdge Full support ≤18Firefox Full support YesIE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
KeyboardEvent() constructorChrome Full support YesEdge Full support ≤79Firefox Full support 31IE No support NoOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 31Opera Android Full support YesSafari iOS ? Samsung Internet Android Full support Yes
altKeyChrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
charCode
DeprecatedNon-standard
Chrome Full support 26Edge Full support 12Firefox Full support 3IE Full support 9Opera Full support 12.1Safari Full support 5.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support 5.1Samsung Internet Android Full support Yes
codeChrome Full support 48Edge Full support 79Firefox Full support 38IE No support NoOpera Full support 35Safari Full support 10WebView Android Full support 48Chrome Android Full support 48Firefox Android Full support 38Opera Android Full support 35Safari iOS Full support 10Samsung Internet Android Full support 5.0
ctrlKeyChrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
getModifierStateChrome Full support 31Edge Full support 12Firefox Full support 15IE Full support 9Opera Full support 17Safari Full support 10.1WebView Android Full support 4.4.3Chrome Android Full support 31Firefox Android Full support 15Opera Android Full support 18Safari iOS Full support 10.3Samsung Internet Android Full support 2.0
isComposingChrome Full support 56Edge Full support ≤79Firefox Full support 31IE No support NoOpera Full support 43Safari Full support 10.1WebView Android Full support 56Chrome Android Full support 56Firefox Android Full support 31Opera Android Full support 43Safari iOS Full support 10.3Samsung Internet Android Full support 6.0
keyChrome Full support 51Edge Full support 12Firefox Full support 23IE Full support 9
Notes
Full support 9
Notes
Notes IE's implementation does not completely match the current spec because it is based on an older version of the spec.
Opera Full support 38Safari Full support 10WebView Android Full support 51Chrome Android Full support 51Firefox Android Full support 23Opera Android Full support 41Safari iOS Full support 10Samsung Internet Android Full support 5.0
keyCode
DeprecatedNon-standard
Chrome Full support 26Edge Full support 12Firefox Full support 3IE Full support 9Opera Full support 12.1Safari Full support 5WebView Android Full support ≤37Chrome Android Full support 26Firefox Android Full support 4Opera Android Full support 12.1Safari iOS Full support 5.1Samsung Internet Android Full support 1.5
keyIdentifier
DeprecatedNon-standard
Chrome No support 26 — 54Edge ? Firefox No support NoIE No support NoOpera No support 15 — 41Safari Full support 5.1WebView Android No support ? — 54Chrome Android No support 26 — 54Firefox Android No support NoOpera Android No support ? — 41Safari iOS Full support 5.1Samsung Internet Android No support 1.5 — 6.0
locationChrome Full support YesEdge Full support 12Firefox Full support 15IE Full support 9Opera Full support YesSafari Full support 6.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 15Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support Yes
metaKeyChrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
repeatChrome Full support YesEdge Full support 79Firefox Full support 28IE No support NoOpera Full support YesSafari Full support 10.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 28Opera Android Full support YesSafari iOS Full support 10.3Samsung Internet Android Full support Yes
shiftKeyChrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
which
DeprecatedNon-standard
Chrome Full support 4Edge Full support 12Firefox Full support 2
Notes
Full support 2
Notes
Notes Firefox also implements this property on the UIEvent interface.
IE Full support 9Opera Full support 12.1Safari Full support 5.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support Yes
Notes
Full support Yes
Notes
Notes Firefox also implements this property on the UIEvent interface.
Opera Android Full support 12.1Safari iOS Full support 5.1Samsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation 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).

参见