javascript - 查找在javascript中按下的键的Unicode

标签 javascript events input unicode keyboard

如何确定在 javascript 中按下的键的 Unicode?

我用谷歌搜索了这个,大多数结果只回答了如何找到 keyCode。任何帮助将不胜感激。

最佳答案

理论上,根据 DOM3 Events ,您应该使用事件对象的 key 属性。实际上,它不起作用,除非在足够新的 IE 版本中。

实用的方法是使用 which 属性或 charCode 属性,即使 DOM3 事件草案不赞成它们:

Browser support for keyboards has traditionally relied on three ad-hoc attributes, keyCode, charCode, and which.

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/

相关文章:

javascript - 通过 jQuery 构建时 Div 的内容格式不同

javascript - 有比 document.execCommand 更好的东西吗?

javascript - 有没有办法在javascript中检测页面搜索中的查找

jquery - 输入Jquery意外结束

javascript - 如何更改jsp <form :input/> via JavaScript with a barcode reader?的焦点

javascript - Bootstrap DateTime Picker 未正确显示其隐藏在屏幕上

javascript - 从 Spotify API 请求 reshresh_token 时如何修复 'error: invalid_grant Invalid authorization code'?

c# - 如何识别 RDP/MSTSC 登录失败的时间?

javascript - 如何从事件监听器获取增加或减少值

javascript - 在 php 循环中单击复选框时将 1 添加到输入值