在移动浏览器中对于keyup,keydown和keypress未定义event.key
以下代码应该简单地抑制任何按键按下,而是将按下的按键添加到div中.
The following code is supposed to simply suppress any key press and add the pressed key to a div instead. This works fine on desktop, however on mobile (safari and chrome) event.key
is undefined.
<html>
<head></head>
<body>
<input />
<div id="#test"></div>
<script>
var str = '';
var el = document.getElementById('#test');
document.addEventListener('keypress', function(event) {
str += event.key;
event.preventDefault();
el.innerHTML = str;
})
</script>
</body>
</html>
event.keyCode
和event.keyIdentifier
都可用,但是将它们强制转换为字符串会在不同的键盘布局和语言(特别是带有特殊字符)上给我带来不必要的结果.
event.keyCode
and event.keyIdentifier
are both available but casting those to a string will give me unwanted results on different keyboard layouts and languages, especially with special characters.
反正有直接获取键值的方法吗?
Is there anyway to get the value of the key directly?
这是一个Codepen示例,以防万一: https://codepen.io/anon/pen/pryYyQ
Here's a codepen example just in case: https://codepen.io/anon/pen/pryYyQ
唯一的解决方法是获取密钥代码并将其转换为String:
The only workaround is to get the keycode and cast it to String:
var str = '';
var el = document.getElementById('#test');
document.addEventListener('keypress', function(event) {
const currentCode = event.which || event.code;
let currentKey = event.key;
if (!currentKey) {
currentKey = String.fromCharCode(currentCode);
}
str += currentKey;
event.preventDefault();
el.innerHTML = str;
})