jquery 如何将字符转换为它的键码?

yrefmtwq  于 11个月前  发布在  jQuery
关注(0)|答案(7)|浏览(232)

如何将一个字符转换为其各自的键码?
举例来说:

  • a65
  • b66的转换
  • c67的转换
  • d68的内存
nzk0hqpo

nzk0hqpo1#

您可以使用charCodeAt函数来实现这一点。
工作示例:

function showKeyCode () {
    var character = document.getElementById("character").value.substring(0, 1);
    var code = document.getElementById("character").value.charCodeAt(0);
    var msg = "The Key Code for the \"" + character + "\" character is " + code + ".";
    alert(msg);
}

个字符

bsxbgnwa

bsxbgnwa2#

你说的“keyCode”是什么意思?不同的浏览器在keyupkeydown事件中有不同的keyCode值,这些值不一定对应于相应字符的ASCII码。对于字母数字键,keypress事件将通过charCodewhich属性给予大多数浏览器中的ASCII码。This page很有用。

2015年9月更新

正如Jan在评论中指出的,keyCode最终将被上级key属性所取代。然而,目前还没有太多的浏览器支持这一点。

qvk1mo1f

qvk1mo1f3#

下面是一个带有一些键和它们对应的键码的对象:

{"0":48,"1":49,"2":50,"3":51,"4":52,"5":53,"6":54,"7":55,"8":56,"9":57,"d":68,"b":66,"a":65,"s":83,"i":73,"f":70,"k":75,"ß":219,"Dead":220,"+":187,"ü":186,"p":80,"o":79,"u":85,"z":90,"t":84,"r":82,"e":69,"w":87,"g":71,"h":72,"j":74,"l":76,"ö":192,"ä":222,"#":191,"y":89,"x":88,"c":67,"v":86,"n":78,"m":77,",":188,".":190,"-":189,"ArrowRight":39,"ArrowLeft":37,"ArrowUp":38,"ArrowDown":40,"PageDown":34,"Clear":12,"Home":36,"PageUp":33,"End":35,"Delete":46,"Insert":45,"Control":17,"AltGraph":18,"Meta":92,"Alt":18,"Shift":16,"CapsLock":20,"Tab":9,"Escape":27,"F1":112,"F2":113,";":188,":":190,"_":189,"'":191,"*":187,"Q":81,"W":87,"E":69,"R":82,"T":84,"Z":90,"S":83,"A":65,"D":68,"I":73,"U":85,"O":79,"Y":89,"X":88,"C":67,"F":70,"V":86,"G":71,"B":66,"H":72,"N":78,"J":74,"M":77,"K":75,"L":76,"P":80,"Ö":192,"Ä":222,"Ü":186,"!":49,"\"":50,"§":51,"$":52,"%":53,"&":54,"/":55,"(":56,")":57,"=":48,"?":219,"°":220}

字符串
如果某些键丢失或与您的浏览器不同,您可以使用以下功能:

let a = {}
document.addEventListener("keydown", ({key, keyCode}) => a[key] = keyCode);


只需将其复制到控制台并将头撞在键盘上。结果将存储在a

u91tlkcl

u91tlkcl4#

正如评论中所指出的:接受的答案是不正确的,因为它给出的是字符代码而不是keyCode,这可能是不同的,例如'a'.charCodeAt(0) == 97,而正确的keyCode是65
如果只需要从[a-zA-Z]或数字[0-9]转换标准字符,可以使用下面的代码。
然而,这不正确的工作,任何特殊的键.Ö#或任何东西,我没有找到一个很好的解决方案。作为一个变通办法,可以使用一个网站,如http://keycode.info/(它只是捕获onkeydown事件和读取event.keyCode属性)。

function convertToKeyCode(target) {
    var keyCode = target.value.toUpperCase().charCodeAt(0);
    document.getElementById("keyCodeSpan").innerHTML = keyCode;
}

个字符

cyej8jka

cyej8jka5#

找到一个像this one这样的keycode/ASCII图表,并将其放入一个数组中,使得array [char '] = keycode。这很繁琐,但代码执行得很快。

raogr8fs

raogr8fs6#

当我偶然发现这个问题时,我正在寻找这个。我不认为标记的答案是正确的答案。对于简单的字母,A-Za-z,我使用以下内容:

function getKeyCode(char) {
  var keyCode = char.charCodeAt(0);
  if(keyCode > 90) {  // 90 is keyCode for 'z'
    return keyCode - 32;
  }
  return keyCode;
}

字符串
请注意,这意味着只适用于字符A-Z和a-z。

vojdkbi0

vojdkbi07#

用途:

let character = prompt('input a character');

console.log(character.charCodeAt(0));

字符串
对于基本概念,您应该使用方法“string.charCodeAt(0”。
例如,在JavaScript中,“A”. charCodeAt(0)。

相关问题