KeyboardEvent.charCode

非标准: 该特性是非标准的,请尽量不要在生产环境中使用它!

已弃用: 不再推荐使用该特性。虽然一些浏览器仍然支持它,但也许已从相关的 web 标准中移除,也许正准备移除或出于兼容性而保留。请尽量不要使用该特性,并更新现有的代码;参见本页面底部的兼容性表格以指导你作出决定。请注意,该特性随时可能无法正常工作。

KeyboardEvent.charCode 只读属性,返回 keypress 事件触发时按下的字符键的字符 Unicode 值。

与这些数值代码等价的常量,请参考 KeyEvent.

备注: 该属性已被废弃,请勿再使用该属性。

请使用 KeyboardEvent.key 取代。

语法

var value = event.charCode;
  • value 被按下的字符键的字符 Unicode 值

示例

js
<html>
<head>
<title>charCode example</title>

<script type="text/javascript">

function showChar(e)
{
alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
      + "charCode: " + e.charCode);
}

</script>
</head>

<body onkeypress="showChar(event);">
<p>Press any 'character' type key.</p>
</body>
</html>

注意

keypress 事件中,按键的 Unicode 值保存在 keyCodecharCode 属性其中之一,不会二者同时都有。如果按下的是字符键 (例如 'a'), charCode 被设置为字符的代码值,并区分大小写。(即 charCode 会考虑 Shift 键是否被按下)。否则,被按下的键的代码被存储在 keyCode 中。

如果有一个或多个修饰键被按下,有一些复杂的规则来产生 charCode 的值,细节可参考 Gecko Keypress 事件

charCode 用于不会在 keydownkeyup 事件中被设置。这两种情况下,keyCode 会被设置。

要获取按键代码而不考虑是 keyCode 还是charCode, 请使用 which 属性。

通过输入法输入的字符,不会被设置到注册到通过 keyCodecharCode。 Actually with the Chinese IME I'm using, entering the IME results in a keypress event with keyCode = 229 and no other key events fire until the IME exits (which may happen after multiple characters are inputted). I'm not sure if other IME's work this way.

要查看特定按键的 charCode 值的列表,运行这个示例页面 Gecko DOM Reference:Examples #Example 7: Displaying Event Object Constants ,然后查看 HTML 表格结果。

规范

Specification
UI Events
# dom-keyboardevent-charcode

浏览器兼容性

BCD tables only load in the browser