这里我有一段简单的代码。我希望它在按下键盘上代表这些字母的按钮时提醒字母 [A-Z]。到目前为止,它只提醒 keyCodes。我知道我可以通过 switch 语句来做到这一点。但是它将是一大段 switch 语句。所以我的问题是:
1.有没有一种方法可以在按键时按字母名称提醒每个字母,而无需使用 switch 语句?
2.左、右、上、下箭头键没有提醒其键码编号。为什么会这样?我该如何克服这个问题?
(function(){
document.body.addEventListener('keypress',function(e){
alert(e.keyCode);
});
})();
最佳答案
要显示其 keyCode 中的字母:
alert (String.fromCharCode(e.keyCode));
要解决箭头键不显示 keyCode
(37 - 40) 的问题:
(function(){
document.body.addEventListener('keyup',function(e){
// the keyCodes of the arrow keys, matched to an appropriate
// unicode arrow symbol:
var directionals = {
'38' : 8593, // String.fromCharCode(38) => &
'39' : 8594, // String.fromCharCode(39) => '
'40' : 8595, // String.fromCharCode(40) => (
'37' : 8592 // String.fromCharCode(37) => %
},
// if there is a falsey value from directionals object,
// we use the e.keyCode unchanged; otherwise we substitute
// e.keyCode for the above-supplied arrow-character:
keyCodeToUse = !directionals[e.keyCode] ? e.keyCode : directionals[e.keyCode];
// I don't like alerts; to access the console (in most browsers) press 'F12':
console.log(String.fromCharCode(keyCodeToUse));
});
})();
html, body {
background-color: rgba(255,255,180, 0.5);
height: 100%;
}
问题本身是(无论出于何种原因)箭头键仅在 keyup
和 keydown
上返回 keyCode,在 上不按键
。此外,使用其键码(如上面的 JavaScript 所示)的 String.fromCharCode()
返回的字符实际上不是箭头。因此,我们必须使用备用 Unicode 引用(上面在 JavaScript 中提供)。
引用文献:
关于javascript - 在不使用 switch 语句的情况下按下键盘按钮时按名称提醒字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25973725/