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

javascript - keycode on keydown event - Stack Overflow

programmeradmin4浏览0评论

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 and charcode as 2

When I press 2 in numpad it gives keycode 98, so when I convert charcode a

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 and charcode as 2

When I press 2 in numpad it gives keycode 98, so when I convert charcode a

Share Improve this question edited Jun 27, 2022 at 17:43 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Oct 30, 2009 at 5:18 SanthoshSanthosh 20.4k23 gold badges66 silver badges76 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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);
};

just look at these solution similar to your requirement

and for keycode reference use this

and keycode is depend on browser check it

you'll get character code in keypress event
try this out: http://www.w3.org/2002/09/tests/keys.html

They use following code to convert to character:

var charCode = (evt.charCode) ? evt.charCode : evt.keyCode;

this also may be helpful as keycodes reference

发布评论

评论列表(0)

  1. 暂无评论