简体   繁体   English

查找在javascript中按下的键的Unicode

[英]Finding the Unicode for the key pressed in javascript

How can one determine the Unicode of the key pressed in javascript? 如何确定javascript中按下的键的Unicode?

I googled on this and most of the results only answer as to how to find the keyCode. 我搜索了这个,大多数结果只回答了如何找到keyCode。 Any help would be greatly appreciated. 任何帮助将不胜感激。

In theory, as per DOM3 Events , you should use the key property of an event object. 理论上,根据DOM3事件 ,您应该使用事件对象的key属性。 In practice, it doesn't work, except in sufficiently new versions of IE. 在实践中,除了足够新的IE版本之外,它不起作用。

The practical approach is to use the which property or the charCode property, even though the DOM3 Events draft frowns upon them: 实际的方法是使用which属性或charCode属性,即使DOM3 Events草案对它们不满意:

Browser support for keyboards has traditionally relied on three ad-hoc attributes, keyCode , charCode , and which . 传统上,浏览器对键盘的支持依赖于三个ad-hoc属性, keyCodecharCodewhich

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. 所有这三个属性都返回一个代表按下keyCode某个方面的数字代码: keyCode是键本身的索引。 charCode is the ASCII value of the character keys. charCode是字符键的ASCII值。 which is the character value where available and otherwise the key index. which是可用的字符值,否则是键索引。 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. 这些属性的值以及属性的可用性在平台,键盘语言和布局,用户代理,版本甚至事件类型之间不一致。

In reality, charCode returns the Unicode value (code number). 实际上, charCode返回Unicode值(代码编号)。

The following simple code can be used to test the functionality (it just echoes the character number in an element on the page): 以下简单代码可用于测试功能(它只是回显页面元素中的字符编号):

<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>

This seems to work in modern browsers, including IE 9 and newer. 这似乎适用于现代浏览器,包括IE 9和更新版本。 For older browsers, you may need to try to do something with keyCode based on a guess of the keyboard mapping. 对于较旧的浏览器,您可能需要尝试根据键盘映射的猜测对keyCode执行某些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM