简体   繁体   中英

Finding the Unicode for the key pressed in javascript

How can one determine the Unicode of the key pressed in javascript?

I googled on this and most of the results only answer as to how to find the keyCode. Any help would be greatly appreciated.

In theory, as per DOM3 Events , you should use the key property of an event object. In practice, it doesn't work, except in sufficiently new versions of IE.

The practical approach is to use the which property or the charCode property, even though the DOM3 Events draft frowns upon them:

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.

In reality, charCode returns the Unicode value (code number).

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. For older browsers, you may need to try to do something with keyCode based on a guess of the keyboard mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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