1

当我从键盘上字母上方的数字中按 8 时,event.which 返回 56,但是当我从侧面给出的数字键盘中按 8 时,它返回 104('h' 的 ascii)。我正在这样做:

var keyPressed = event.which;
String.fromCharCode(keyPressed); // returns 8 from keyboard, 'h' from keypad

我在keydown事件的处理程序中执行此操作。现在,我知道键盘上的每个键都有一个不同的 keyCode,并且可能是 event.which 返回 numpad 8 的 keyCode,它恰好与 ascii 'h' 一致。我只想让 8 返回,而不管它是从哪里输入的。

此外,我无法将上述代码绑定到 keyPress 事件处理程序,因为它不会捕获 IE 中的删除、制表符等。

4

2 回答 2

0

There is a better way to detect which key was pressed in JavaScript / jQuery.

First, on a general note, the keydown event is more effective at getting all the keys you want, as keypress won't necessarily fire on ENTER, ESC, TAB, arrow keys, etc.

To detect numbers from either the numeric keypad OR the line of numbers above the QWERTY keyboard, use:

event.keyIdentifier

or, with jQuery wrapped events:

event.originalEvent.keyIdentifier

"event" in these examples is the keydown event object.

This will give you a unicode string value representing the actual character of the key:

U+002F or U+0035, for example. Then, parse this unicode value as a hexidecimal number:

parseInt(event.keyIdentifier.substring(2),16)

Using 16 as the radix for parseInt will convert the hexidecimal number to a base-10.

With this method, all number keys will have the same value, whether they originate from the numberpad or the QWERTY keyboard. Numbers 0 - 9 are 48 - 57. So, an if() statement like this will find all numbers:

if (parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58) {
    doSomething();
}
于 2014-02-07T18:13:14.357 回答
0

Ascii 代码和字符代码是两个不同的东西。小键盘“8”产生的字符代码为 104,“h”为 72。每个键都有不同的数字,因此 h 将始终为 72。

字符代码

Jquery Docs JQuery event.which中有一个很好的例子

于 2011-11-30T08:01:26.443 回答