非标
此特征是非标准的,且不在标准轨道中。不要在面向 Web 的生产站点中使用它:它不适用于每个用户。实现之间可能存在大的不兼容性,且行为将来可能改变。
弃用
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the
兼容性表格
at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
charCode
只读特性在
KeyboardEvent
interface returns the Unicode value of a character key pressed during a
keypress
事件。
Do not use this property, as it is deprecated.
使用
key
特性代替。
var code = event.charCode;
A number that represents the Unicode value of the character key that was pressed.
<p>Type anything into the input box below to log a <code>charCode</code>.</p> <input type="text" /> <p id="log"></p>
let input = document.querySelector('input');
let log = document.querySelector('#log');
input.addEventListener('keypress', function(e) {
log.innerText = `Key pressed: ${String.fromCharCode(e.charCode)}\ncharCode: ${e.charCode}`;
});
keypress
event, the Unicode value of the key pressed is stored in either the
keyCode
or
charCode
property, but never both. If the key pressed generates a character (e.g., 'a'),
charCode
is set to the code of that character;
charCode
respects the letter case (in other words,
charCode
takes into account whether the
shift
key is held down). Otherwise, the code of the pressed key is stored in
keyCode
.
charCode
。见
Gecko Keypress Event
了解细节。
charCode
is never set in the
keydown
and
keyup
events. In these cases,
keyCode
is set instead.
keyCode
or
charCode
, query the
which
特性。
keyCode
or
charCode
.
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
values associated with particular keys, run
Example 7: Displaying Event Object Properties
and view the resulting HTML table.
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM (文档对象模型) 3 级事件规范
The definition of 'KeyboardEvent.charCode' in that specification. |
过时 | Initial definition; specified as deprecated |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
非标。预期跨浏览器支持较差。
弃用。不要用于新网站。