我的功能将键码转换为键盘键时遇到了一些问题。我最初有一个巨大的 switch 语句,如果代码是 37,我的程序将输出“左箭头键”。我的问题是,不同的浏览器不会触发某些按键,有时代码会混淆。例如,在运行 Chrome 的 Mac 上 shift + 7 会输出代码 37,即向左箭头键。mac 上的 Firefox 不会告诉我是否按下了 tab 键等。
这是我正在使用的代码:
function getKey(code) {
var keyPress;
// In case of special keys
switch (code)
{
case 8:
keyPress = " backspace ";
break;
case 9:
keyPress = " tab ";
break;
case 13:
keyPress = " enter ";
break;
case 16:
keyPress = " shift ";
break;
case 17:
keyPress = " control ";
break;
case 18:
keyPress = " alt ";
break;
case 20:
keyPress = " caps lock ";
break;
case 27:
keyPress = " escape ";
break;
case 46:
keyPress = " delete ";
break;
case 37:
keyPress = " left arrow key ";
break;
case 38:
keyPress = " up arrow key ";
break;
case 39:
keyPress = " right arrow key ";
break;
case 40:
keyPress = " down arrow key ";
break;
case 45:
keyPress = " insert ";
break;
case 46:
keyPress = " delete ";
break;
case 91:
keyPress = " command ";
break;
default:
keyPress = String.fromCharCode(code);
}
return keyPress;
}
$(document).keypress(function(e) {
var code = e.which;
var keyPress = String.fromCharCode(code);
$(".keystrokes").append(keyPress);
});
那么,是否有任何 jquery 库可以准确地给我正确按下的键?