Javascript 数字键盘按键代码解析

发布于 2025-01-06 20:59:14 字数 282 浏览 0 评论 0原文

我正在尝试使用以下内容解析数字键盘中的 keydown 事件:

$('#myDiv').keydown(function(e) {
  val = String.fromCharCode(e.which)
});

问题是键盘 0-9 返回 96-105 的 keyCodes,根据 fromCharCode () 是小写字母 ai。如何获取数字键盘的按键事件以解析为适当的数字?

I am attempting to parse keydown events from the numberpad with the following:

$('#myDiv').keydown(function(e) {
  val = String.fromCharCode(e.which)
});

The problem is that keypad 0-9 return keyCodes of 96-105 which, according to fromCharCode() are the lower case letters a-i. How do I get keydown events of the numberpad to resolve to the appropriate number?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

秋风の叶未落 2025-01-13 20:59:14

您不需要:您使用 keypress 事件。 keypress 事件是唯一可以为您提供有关键入字符的可靠信息的事件。如果您只需将 keydown 更改为 keypress,您现有的代码就可以工作。

You don't: you use the keypress event. The keypress event is the only event that will give you reliable information about typed characters. Your existing code will work if you simply change keydown to keypress.

半世晨晓 2025-01-13 20:59:14

传递给 keydownwhich 值不是字符代码;它是一个关键代码(代码因浏览器/操作系统而异)。您可以使用此页面上的表格将其映射到字符,但要说的是,这个东西是有点……尴尬……轻描淡写了。 :-)

否则,最好的办法是等待 keypress 事件,该事件将包含字符代码(如果相关)而不是按键代码。

示例:实时副本 | 实时源

jQuery(function($) {

  $("#theField")
    .keydown(function(event) {
      showKey("keydown", event.which);
    })
    .keypress(function(event) {
      showKey("keypress", event.which);
    })
    .focus();

  function showKey(eventName, which) {
    display(eventName +
            ": " + which + " (" +
            String.fromCharCode(which) + ")");
  }

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

使用此 HTML:

<input type="text" id="theField">

The which value passed to keydown is not a character code; it's a key code (and the codes vary from browser/OS to browser/OS). You can map it to a character using the tables on this page, but to say that this stuff is a bit...awkward...would be to understate the case. :-)

Otherwise, your best bet is to wait for the keypress event, which will have the character code (if relevant) rather than a key code.

Example: Live copy | Live source

jQuery(function($) {

  $("#theField")
    .keydown(function(event) {
      showKey("keydown", event.which);
    })
    .keypress(function(event) {
      showKey("keypress", event.which);
    })
    .focus();

  function showKey(eventName, which) {
    display(eventName +
            ": " + which + " (" +
            String.fromCharCode(which) + ")");
  }

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

Using this HTML:

<input type="text" id="theField">
小巷里的女流氓 2025-01-13 20:59:14

这里的答案现在已经过时了,因为 KeyboardEvent.whichKeyboardEvent.keyCodeKeyboardEvent.charCode 均已弃用。

最新版本的 Firefox、Chrome、IE/Edge 和 Safari 获取字符密钥的正确方法是使用 KeyboardEvent.key 并且它应该适用于任何按键事件,而不仅仅是 keypress

KeyboardEvent.key 浏览器兼容性

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.key));
<input placeholder="Start typing...">


如果您仍然需要获取字符代码,您应该使用 KeyboardEvent.code 属性。

KeyboardEvent.code 浏览器兼容性

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.code));
<input placeholder="Start typing...">

The answers here are now outdated because KeyboardEvent.which, KeyboardEvent.keyCode and KeyboardEvent.charCode are all deprecated.

The proper way for the latest versions of Firefox, Chrome, IE/Edge and Safari to obtain the character key is to use KeyboardEvent.key and it should work with any key event, not just keypress.

KeyboardEvent.key Browser Compatibility

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.key));
<input placeholder="Start typing...">


If you still need to obtain the character code, you should use the KeyboardEvent.code property.

KeyboardEvent.code Browser Compatibility

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.code));
<input placeholder="Start typing...">

那片花海 2025-01-13 20:59:14

如果由于需要取消事件而无法使用 keypress,则有一种方法可以使用 keydown 来执行此操作。在此测试中使用 if() 语句:

parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58

或者,使用 jQuery 事件:

parseInt(event.originalEvent.keyIdentifier.substring(2),16) > 47 && parseInt(event.originalEvent.keyIdentifier.substring(2),16) < 58

这些示例假设“event”是 keydown 事件。 keyIdentifier 是一个十六进制数字,表示相关字符的 unicode 值。使用 keyIdentifier,数字键盘/小键盘上的数字以及 QWERTY 键盘上方的数字都将具有相同的值,48 - 57 (U+0030 - U+0039),即使有 keyDown 事件也是如此。

浏览器中的 Unicode 值将类似于 U+0030 或 U+002F。解析该字符串仅获取十六进制值,然后使用基数为 16 的 parseInt() 将其转换为基数 10。

There is a way to do this with keydown, if keypress is not workable due to event canceling needs, etc. Use an if() statement with this test:

parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58

OR, with jQuery events:

parseInt(event.originalEvent.keyIdentifier.substring(2),16) > 47 && parseInt(event.originalEvent.keyIdentifier.substring(2),16) < 58

These examples assume "event" is the keydown event. keyIdentifier is a hexidecimal number that represents the unicode value for the related char. Using keyIdentifier, numbers from the numberpad / keypad AND the numbers above your QWERTY keyboard will all have the same values, 48 - 57 (U+0030 - U+0039), even with the keyDown event.

Unicode values in the browsers will look like U+0030 or U+002F. Parse this string to only get the hexidecimal value, then use parseInt() with a radix of 16 to convert it to base-10.

戴着白色围巾的女孩 2025-01-13 20:59:14

您可以使用 keydown 并检测数字键盘键。我使用以下代码完成了它。在解释按键之前从数字键盘按键中减去 48

function navigate(e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode >= 96 && keyCode <= 105) {
            // Numpad keys
            keyCode -= 48;
        }  
        var txtVal = String.fromCharCode(keyCode);

you can use keydown and detect numpad keys. I did it using following code. Subtract 48 from numpad keys before interpreting the key

function navigate(e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode >= 96 && keyCode <= 105) {
            // Numpad keys
            keyCode -= 48;
        }  
        var txtVal = String.fromCharCode(keyCode);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文