keydown事件的键码 [英] keycode on keydown event

查看:121
本文介绍了keydown事件的键码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用keydown事件

I'm using keydown event

哪里可以获取密码并将其转换为charcode。

Where I get the keycode and convert it to charcode.

但是我有一个问题,键盘是按 2 它给 50 和charcode为 2

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

当我在numpad中按 2 时,它会提供keycode 98 ,所以当我转换charcode a

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

推荐答案

这是因为您使用 keyCode 成员,例如,小写a和大写A具有相同的keyCode,因为是相同的键,但不同的charCode,因为结果字符是不同的。

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.

要获取charCode,您应该使用 keypress 事件,并获取 event.charCode 成员(如果可用),否则您将获得 event.keyCode 对于IE,在keypress事件中有正确的信息。

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.

查看以下示例

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

  alert(character);
};

这篇关于keydown事件的键码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆