根据本文档:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
...确定KeyboardEvent
字符的正确方法是使用event.key
。问题是,当我在iOS上测试我的代码时(从我到目前为止所读的内容来看,在其他移动平台上都是如此),event.key
是undefined
。
还有event.code
,它不被弃用,但这告诉您键的物理位置,不一定是实际键入的字符。 (例如,KeyQ
可以表示字母“ q”,但也可以是“ Q”或单引号,也可以是“ a”或“ A”,具体取决于键盘以及是否按下了Shift
。
因此,我发现自己不得不依靠已弃用的event.charCode
,event.keyCode
和event.which
。有没有更好的办法?以下代码似乎是一个合理的解决方案吗?
export function eventToKey(event: KeyboardEvent): string {
let key = event.key;
if (key === undefined) {
const charCode = event.charCode;
if (charCode !== 0) {
key = String.fromCodePoint(charCode);
}
else {
const keyCode = event.keyCode || event.which;
switch (keyCode) {
case 8: key = 'Backspace'; break;
case 9: key = 'Tab'; break;
case 12: key = 'Clear'; break;
case 13: key = 'Enter'; break;
case 16: key = 'Shift'; break;
case 17: key = 'Control'; break;
case 18: key = 'Alt'; break;
case 19: key = 'Pause'; break;
case 20: key = 'CapsLock'; break;
case 27: key = 'Escape'; break;
case 33: key = 'PageUp'; break;
case 34: key = 'PageDown'; break;
case 35: key = 'End'; break;
case 36: key = 'Home'; break;
case 37: key = 'ArrowLeft'; break;
case 38: key = 'ArrowUp'; break;
case 39: key = 'ArrowRight'; break;
case 40: key = 'ArrowDown'; break;
case 44: key = 'PrintScreen'; break;
case 45: key = 'Insert'; break;
case 46: key = 'Delete'; break;
case 91: key = 'OS'; break;
case 93: key = 'ContextMenu'; break;
case 144: key = 'NumLock'; break;
case 145: key = 'ScrollLock'; break;
case 224: key = 'Meta'; break;
default:
if (112 <= keyCode && keyCode <= 135)
key = 'F' + (keyCode - 111);
}
}
}
else {
switch (key) {
case 'Left':
case 'UIKeyInputLeftArrow': key = 'ArrowLeft'; break;
case 'Up':
case 'UIKeyInputUpArrow': key = 'ArrowUp'; break;
case 'Right':
case 'UIKeyInputRightArrow': key = 'ArrowRight'; break;
case 'Down':
case 'UIKeyInputDownArrow': key = 'ArrowDown'; break;
case 'Add': key = '+'; break;
case 'Subtract': key = '-'; break;
case 'Multiply': key = '*'; break;
case 'Divide': key = '/'; break;
case 'Decimal': key = '.'; break;
case 'Apps': key = 'ContextMenu'; break;
case 'Del ': key = 'Delete'; break;
case 'Esc': key = 'Escape'; break;
case 'Scroll': key = 'ScrollLock'; break;
case 'Spacebar': key = ' '; break;
case 'Win': key = 'Meta'; break;
}
}
return key;
}
已更新:添加了代码,以覆盖键名中的IE / Edge不一致,以及箭头键的至少一个移动蓝牙键名。