我试图比较2个字符(或键码)来检查屏幕上的字母是否与按下的字符相同。
遗憾的是,所有keyDown结果都是大写的,我想知道是否有一种不同的方式将输入作为小写而不是手动更改所有输入。
这是我的代码:
document.onkeydown = function keyDown(e) {
if (!e) e = window.event;
if (e.keyCode == currentCharacter.charCodeAt(0)) {
// Input matches the current character.
} else {
// Input does not match the current character.
}
}
在此示例中,e.keyCode始终返回我按下的字符的大写版本的键代码。
使用keyPress
事件而不是keyDown
可能是答案。
如何将keyCode转换为char,并将其小写为..
document.onkeydown = function keyDown(e) {
if (!e) e = window.event;
var keyPressed = String.fromCharCode(e.keyCode).toLowerCase()
if (keyPressed == 'a') {
// Input matches the current character.
} else {
// Input does not match the current character.
}
}