如何确定在 javascript 中按下的键的 Unicode?p>
我用谷歌搜索了这个,大多数结果只回答了如何找到 keyCode。任何帮助将不胜感激。
最佳答案
理论上,根据 DOM3 Events ,您应该使用事件对象的 key
属性。实际上,它不起作用,除非在足够新的 IE 版本中。
实用的方法是使用 which
属性或 charCode
属性,即使 DOM3 事件草案不赞成它们:
Browser support for keyboards has traditionally relied on three ad-hoc attributes,
keyCode
,charCode
, andwhich
.All three of these attributes return a numerical code that represents some aspect of the key pressed:
keyCode
is an index of the key itself.charCode
is the ASCII value of the character keys.which
is the character value where available and otherwise the key index. The values for these attributes, and the availability of the attribute, is inconsistent across platforms, keyboard languages and layouts, user agents, versions, and even event types.
实际上,charCode
返回 Unicode 值(代码编号)。
以下简单代码可用于测试功能(它只是在页面元素中回显字符编号):
<style>
#o { border: solid black 1px; }
</style>
<input id=i>
<div id=o></div>
<script>
document.getElementById('i').onkeypress = function (e) {
var ev = e || window.event;
document.getElementById('o').innerHTML +=
ev.charCode + ' ';
}
</script>
这似乎适用于现代浏览器,包括 IE 9 和更新版本。对于较旧的浏览器,您可能需要根据对键盘映射的猜测尝试使用 keyCode
执行某些操作。
关于javascript - 查找在javascript中按下的键的Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609729/