KeyboardEvent 接口的 key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout. Its value is determined as follows:

Key values

See a full list of key values .

  • If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.
  • If the pressed key is a control or special character, the returned value is one of the pre-defined key values .
  • KeyboardEvent represents the press of a dead key , the key value must be " Dead ".
  • Some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don't generate key codes on Windows; instead, they trigger WM_APPCOMMAND events. These events get mapped to DOM keyboard events, and are listed among the "Virtual key codes" for Windows, even though they aren't actually key codes.
  • If the key cannot be identified, the returned value is Unidentified .

KeyboardEvent sequence

每个 KeyboardEvent is fired in a pre-determined sequence. For a given key press, the sequence of KeyboardEvent s fired is as follows assuming that Event.preventDefault is not called:

  1. keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true .
  2. If the key produces a character key that would result in a character being inserted into possibly an <input> , <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
  3. keyup event is fired once the key is released. This completes the process.

In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined ealier.

KeyboardEvent sequence example

Consider the event sequence generated when we interact with the Shift 2 key using a U.S keyboard layout as compared to when we do so using a UK keyboard layout.

Try experimenting using the following two test cases:

  1. Press and hold the Shift key, then press 2 and release it. Next, release the Shift key.
  2. Press and hold the Shift key, then press and hold 2 . Release the Shift key. Finally, release 2 .

HTML

<div class="fx">
  <div>
    <textarea rows="5" name="test-target" id="test-target"></textarea>
    <button type="button" name="btn-clear-console" id="btn-clear-console">clear console</button>
  </div>
  <div class="flex">
    <pre id="console-log"></pre>
  </div>
</div>
						

CSS

.fx {
  -webkit-display: flex;
  display: flex;
  margin-left: -20px;
  margin-right: -20px;
}
.fx > div {
  padding-left: 20px;
  padding-right: 20px;
}
.fx > div:first-child {
   width: 30%;
}
.flex {
  -webkit-flex: 1;
  flex: 1;
}
#test-target {
  display: block;
  width: 100%;
  margin-bottom: 10px;
}
						

JavaScript

let textarea = document.getElementById('test-target'),
consoleLog = document.getElementById('console-log'),
btnClearConsole = document.getElementById('btn-clear-console');
function logMessage(message) {
  document.getElementById("console-log").innerHTML += message + "<br>";
}
textarea.addEventListener('keydown', (e) => {
  if (!e.repeat)
    logMessage(`Key "${e.key}" pressed  [event: keydown]`);
  else
    logMessage(`Key "${e.key}" repeating  [event: keydown]`);
});
textarea.addEventListener('beforeinput', (e) => {
  logMessage(`Key "${e.data}" about to be input  [event: beforeinput]`);
});
textarea.addEventListener('input', (e) => {
  logMessage(`Key "${e.data}" input  [event: input]`);
});
textarea.addEventListener('keyup', (e) => {
  logMessage(`Key "${e.key}" released  [event: keyup]`);
});
btnClearConsole.addEventListener('click', (e) => {
  let child = consoleLog.firstChild;
  while (child) {
   consoleLog.removeChild(child);
   child = consoleLog.firstChild;
  }
});
						

结果

注意: On browsers that don't fully implement the InputEvent interface which is used for the beforeinput and input events, you may get incorrect output on those lines of the log output.

Case 1

When the shift key is pressed, a keydown event is first fired, and the key property value is set to the string Shift . As we keep holding this key, the keydown event does not continue to fire repeatedly because it does not produce a character key.

key 2 is pressed, another keydown event is fired for this new key press, and the key property value for the event is set to the string @ for the U.S keyboard type and " for the UK keyboard type, because of the active modifier shift key. The beforeinput and input events are fired next because a character key has been produced.

As we release the key 2 keyup event is fired and the key property will maintain the string values @ and " for the different keyboard layouts respectively.

As we finally release the shift key, another keyup event is fired for it, and the key attribute value remains Shift .

Case 2

When the shift key is pressed, a keydown event is first fired, and the key property value is set to be the string Shift . As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.

key 2 is pressed, another keydown event is fired for this new key press, and the key property value for the event is set to be the string @ for the U.S keyboard type and " for the UK keyboard type, because of the active modifier shift key. The beforeinput and input beforeinput and input events are fired next because a character key has been produced. As we keep holding the key, the keydown event continues to fire repeatedly and the KeyboardEvent.repeat property is set to true beforeinput and input events are fired repeatedly as well.

As we release the shift key, a keyup event is fired for it, and the key attribute value remains Shift . At this point, notice that the key property value for the repeating keydown event of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the InputEvent.data 特性为 beforeinput and input 事件。

As we finally release the key 2 keyup event is fired but the key property will be set to the string value 2 for both keyboard layouts because the modifier shift key is no longer active.

范例

此范例使用 EventTarget.addEventListener() to listen for keydown events. When they occur, the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }
  switch (event.key) {
    case "Down": // IE/Edge specific value
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "Up": // IE/Edge specific value
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "Left": // IE/Edge specific value
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "Right": // IE/Edge specific value
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Esc": // IE/Edge specific value
    case "Escape":
      // Do something for "esc" key press.
      break;
    默认:
      return; // Quit when this doesn't handle the key event.
  }
  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);
						

规范

规范 状态 注释
UI Events
The definition of 'KeyboardEvent.key' in that specification.
工作草案
DOM (文档对象模型) 3 级事件规范
The definition of 'KeyboardEvent.key' in that specification.
过时 Initial definition, included key values.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
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
Dead key Chrome 51 Edge ≤79 Firefox No IE No Opera 38 Safari ? WebView Android 51 Chrome Android 51 Firefox Android No Opera Android 41 Safari iOS ? Samsung Internet Android 5.0
Non-printable keys 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 ? WebView Android 51 Chrome Android 51 Firefox Android 23 Opera Android 41 Safari iOS ? Samsung Internet Android 5.0
Printable keys Chrome 51 Edge 12 Firefox 29 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 ? WebView Android 51 Chrome Android 51 Firefox Android 29 Opera Android 41 Safari iOS ? Samsung Internet Android 5.0

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

见实现注意事项。

元数据

  • 最后修改:
  1. KeyboardEvent
  2. 构造函数
    1. KeyboardEvent()
  3. 特性
    1. altKey
    2. charCode
    3. code
    4. ctrlKey
    5. isComposing
    6. key
    7. keyCode
    8. keyIdentifier
    9. location
    10. metaKey
    11. repeat
    12. shiftKey
    13. which
  4. 方法
    1. getModifierState()
    2. initKeyboardEvent()
    3. initKeyEvent()
  5. 继承:
    1. UIEvent
    2. 事件
  6. DOM 事件相关页面
    1. CompositionEvent
    2. 事件
    3. EventListener
    4. EventTarget
    5. FocusEvent
    6. InputEvent
    7. MouseEvent
    8. MouseScrollEvent
    9. MouseWheelEvent
    10. MutationEvent
    11. ProgressEvent
    12. UIEvent
    13. WheelEvent

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1