如何将字符转换为相应的键码?
例如:
a
至65
b
至66
c
至67
d
至68
答案 0 :(得分:34)
您可以使用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);
}
<input type="text" id="character" size="15">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
答案 1 :(得分:13)
“keyCode”是什么意思?不同的浏览器在keyCode
和keyup
事件中具有不同的keydown
值,这些值不一定对应于相应字符的ASCII码。对于字母数字键,keypress
事件将通过charCode
或which
属性在大多数浏览器中为您提供ASCII代码。 This page很有用。
2015年9月更新
正如Jan在评论中所指出的那样,keyCode
最终将被上级key
属性所取代。但是,目前还没有太多的浏览器支持。
答案 2 :(得分:2)
找到像this one这样的keycode / ascii图表,并将其放入一个数组,使得array ['char'] = keycode。这很乏味,但代码执行得非常快。
答案 3 :(得分:2)
正如评论中所指出的那样:接受的答案不正确,因为它给出了字符代码而不是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;
}
&#13;
<input type="text" oninput="convertToKeyCode(this)" size="1" maxlength="1">
<span>Keycode: </span><span id="keyCodeSpan"></span>
&#13;
答案 4 :(得分:1)
当我偶然发现这个问题时,我正在寻找这个。我认为标记的答案不是正确的答案。对于简单的字母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。
答案 5 :(得分:1)
这是一个带有一些键及其对应键码的对象:
{"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