MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

KeyboardEvent.key

这篇翻译不完整。请帮忙从英语翻译这篇文章

草案
本页尚未完工.

译者注:这个API和keycode、which的区别是:这个API返回的是键名,而不是键值,如返回Enter而不是13。

KeyboardEvent.key 返回用户按下的键盘物理按键的值。值的决定方式:

查看所有的 键值

  • 如果按下的是一个可打印字符,则返回一个非空的Unicode代表这个字符的字符。
  • 如果按下的是特殊键(如control或特殊字符),则返回值在pre-defined key values这个列表中列出。
  • 如果KeyboardEvent显示是一个死键(dead key),返回值是“dead”。
  • 如果多个键一起按下,这些键里包含可打印的字符,则只会返回这个可打印的字符。如组合键是Control + a,返回的值就是“a“。
  • 有些特殊的键(比如扩展的多媒体键) 在Windows上不会产生键值;但是会触发WM_APPCOMMAND事件,Windows把这些虚拟按键的事件映射到DOM的键盘事件中,尽管他们没有keycode。
  • 如果无法识别,返回"Unidentified"。

本页面正在快速迭代布局,内容等以达到内容的时效性。更新会放置在页面顶部,如果想查看以前的版本,请查阅Previous versions of tables,本页面完成更新的时候,会移除这个历史信息。

例子

这个例子使用EventTarget.addEventListener()监听keydown事件。当我们关注的按键被按下时,会打印预先写好的信息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 "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Escape":
      // Do something for "esc" key press.
      break;
    default:
      return; // Quit when this doesn't handle the key event.
  }

  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);

规范

Specification Status Comment
Document Object Model (DOM) Level 3 Events Specification
KeyboardEvent.key
Working Draft Initial definition, included key values.

兼容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support

51.0

(Yes) 23.0 (23.0) 9.0[1] 38.0 未实现 [2]
non-printable keys 51.0 ? 23.0 (23.0) 9.0[1] 38.0 未实现
printable keys 51.0 ? 29.0 (29.0) 9.0[1] 38.0 未实现
dead key 51.0 ? 未实现 未实现 38.0 未实现
Feature Android Android Webview Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support 未实现 51.0 (Yes) 23.0 (23.0) ? 38.0 未实现 [2] 51.0
non-printable keys of virtual keyboard 未实现 51.0 ? 23.0 (23.0) ? 38.0 未实现 51.0
printable keys of virtual keyboard 未实现 51.0 ? ? ? 38.0 未实现 51.0
non-printable keys of physical keyboard 未实现 51.0 ? 23.0 (23.0) ? 38.0 未实现 51.0
printable keys of physical keyboard 未实现 51.0 ? 29.0 (29.0) ? 38.0 未实现 51.0

[1]: Internet Explorer's implementation does not completely match the current spec because it is based on an older version of the spec.

[2]: WebKit bug #69029

文档标签和贡献者

标签: 
 此页面的贡献者: maicss, Dcfm
 最后编辑者: maicss,