最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Converting keystrokes gathered by onkeydown into characters in JavaScript - Stack Overflow

programmeradmin2浏览0评论

I try to convert keystrokes into chracters. In other question someone remand to use the onkeydown function because onkeypress gets handeled differently by different characters.

I don't know how to handle special chracters like ´ ` ' ( ) that might be different in different keyboards around the world.

I try to convert keystrokes into chracters. In other question someone remand to use the onkeydown function because onkeypress gets handeled differently by different characters.

I don't know how to handle special chracters like ´ ` ' ( ) that might be different in different keyboards around the world.

Share Improve this question asked Sep 16, 2009 at 22:39 ChristianChristian 26.5k43 gold badges140 silver badges231 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

For keys that have printable character equivalents, you should use the keypress event because you can retrieve character codes from the keypress event, which is generally not possible for keyup and keydown events.

The event properties you need are which and keyCode - pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode but it seems all such browsers also have which, so charCode is never needed. A simple example:

document.onkeypress = function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
};

Here is a useful reference page.

 document.onkeydown = checkKey;
function checkKey(e) {

e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
    //a
    var lx = document.getElementById('location');
    typeIt("a");
}
else if (e.keyCode == '66') {
    //b
      var lx = document.getElementById('location');
    typeIt("b");
}
else if (e.keyCode == '67') {
   //c
      var lx = document.getElementById('location');
    typeIt("c");
}
}

This should successfully convert the key code you press into a string letter, which you can use in a bigger function. It takes more time, but I found it is highly patible with most browsers and keyboards (whatever the language may be.) I used this code in a text editor project which would be distributed to friends in several countries, so I am certain it will work. Note: the function above only includes the letters "A", "B", and "C".

发布评论

评论列表(0)

  1. 暂无评论