【问题标题】:Converting Javascript Key Code to Char and vice versa将 Javascript 密钥代码转换为字符,反之亦然
【发布时间】:2018-01-14 22:33:34
【问题描述】:

我正在处理 HTML 输入过滤,我有以下情况:

我需要将 keyCodes 转换为字符,但是当我处理 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 

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

我在这里错过了什么?

【问题讨论】:

标签: javascript keycode


【解决方案1】:

使用ASCII 表获取字符代码。

【讨论】:

    【解决方案2】:

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

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

    查看 man ascii

    【讨论】:

    • 我的意思是您可能正在查看错误的 ascii 字符数字。没有冒犯的意思:)。
    • 是的,谢谢 :) 我对 keyCodes 和 ASCII 码感到困惑(因为 String.fromCharCode 文档没有提及任何相关内容)
    【解决方案3】:

    好的,因此根据网络上的几个来源,我应该执行以下逻辑:

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

    奇怪的是,String.fromCharCode 函数文档没有说明任何内容:(

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多