keycode on keydown event

前端 未结 3 1702
我在风中等你
我在风中等你 2020-12-06 18:07

I\'m using keydown event

Where I get the keycode and convert it to charcode.

But I got a problem where in keyboard is press 2 it gives 50

3条回答
  •  死守一世寂寞
    2020-12-06 18:53

    That is happening because you are using the keyCode member, for example, a lower case 'a' and an upper case 'A' have the same keyCode, because is the same key, but a different charCode because the resulting character is different.

    To get the charCode, you should use the keypress event, and get the event.charCode member if available, otherwise, you get the event.keyCode which for IE, on the keypress event has the right information.

    Give a look to the following example:

    document.onkeypress = function (e) { 
      e = e || window.event; 
      var charCode = e.charCode || e.keyCode, 
          character = String.fromCharCode(charCode); 
    
      alert(character);
    };
    

提交回复
热议问题