将Javascript密钥代码转换为Char,反之亦然

时间:2018-01-14 22:33:34

标签: javascript keycode

我正在进行HTML输入过滤,我遇到以下情况:

我需要将keyCodes转换为chars,但是当我处理Numpad键时,我得到了奇怪的结果:

String.fromCharCode(96) //should be 0 but I recieve "`"
String.fromCharCode(97) //should be 1 but I recieve "a"
String.fromCharCode(98) //should be 2 but I receive "b"
String.fromCharCode(99) //should be 3 but I recieve "c"
String.fromCharCode(100) //should be 4 but I recieve "d"
String.fromCharCode(101) //should be 5 but I recieve "e"
String.fromCharCode(102) //should be 6 but I recieve "f"
String.fromCharCode(103) //should be 7 but I recieve "g"

从文档和事件调试中我可以看到以下映射:

numpad 0    96
numpad 1    97
numpad 2    98
numpad 3    99
numpad 4    100
numpad 5    101
numpad 6    102
numpad 7    103 

link:https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

我在这里缺少什么?

3 个答案:

答案 0 :(得分:1)

使用ASCII表获取字符代码。

答案 1 :(得分:0)

可能只是一个愚蠢的错误。您应该看到的Charcode的数字是48-57。

for ( let i = 0; i < 10; i++ ) {
  console.log( String.fromCharCode( 48 + i ) );
}

见man ascii

答案 2 :(得分:0)

好的,所以相应的网络来源我应该做以下逻辑:

if(keyCode >= 96 && keyCode <= 105){
    keyCode -= 48;
}

奇怪String.fromCharCode函数文档没有说出任何内容:(

相关问题