跳到主要内容

get event char code

/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
*
* `charCode` 表示实际的“字符编码”,可安全用于 `String.fromCharCode`。因此,只有对应可打印字符的按键才会生成有效的 `charCode`,唯一的例外是回车键。
*
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* Tab键被认为是不可打印的,并且没有 `charCode`,* 大概是因为它在浏览器中不会产生制表符。
*
* @param {object} nativeEvent Native browser event.
* nativeEvent 原生浏览器事件。
* @return {number} Normalized `charCode` property.
* 标准化的 `charCode` 属性。
*/
function getEventCharCode(nativeEvent: KeyboardEvent): number {
let charCode;
const keyCode = nativeEvent.keyCode;

if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;

// FF does not set `charCode` for the Enter-key, check against `keyCode`.
// FF 不会为回车键设置 `charCode`,请检查 `keyCode`。
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
// IE8 不支持 `charCode`,但 `keyCode` 有正确的值。
charCode = keyCode;
}

// IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
// report Enter as charCode 10 when ctrl is pressed.
// IE 和 Edge(在 Windows 上)以及 Chrome / Safari(在 Windows 和 Linux 上)
// 当按下 ctrl 时,报告 Enter 为 charCode 10。
if (charCode === 10) {
charCode = 13;
}

// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
// 一些不可打印的按键会在 `charCode`/`keyCode` 中被报告,丢弃它们。
// 不能丢弃(不可打印的)回车键。
if (charCode >= 32 || charCode === 13) {
return charCode;
}

return 0;
}

export default getEventCharCode;