keypress 和 keydown 通过 event.which 提供不同的代码

keypress and keydown providing different codes via event.which

我使用的是 firefox,当我使用 event.which 找出是什么键导致事件触发时,我在检查 event.which 按键事件和按键事件时得到了不同的代码。

使用“-”键时 (hyphen/minus)。当基于按键事件进行报告时,event.which 的值为 45,但基于按键事件进行报告时的值为 173。

对于按键,如果预期代码的值大于 128,我会得到错误的代码(我得到 expected_code & 0x7f)。但是,如果我使用 keydown 做同样的事情,我会得到预期的代码。

JSFiddle: http://jsfiddle.net/fzd3fjqm/1/

html:

<input id="whichkey" value="type something">
<div id="log"></div>
<div id="log2"></div>

javascript:

$( "#whichkey" ).on( "keypress", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log2" ).html( event.type + ": " + event.which )
});

这是预期的吗?

我正在编写一个基于 event.which 的按键和过滤键触发的函数,但它不能很好地处理所描述的行为。

如果这是预料之中的,那么通过按键触发的功能确定按下哪个键的正确方法是什么?

是的,每个事件的 keyCode 都不同(并且因浏览器而异):http://www.quirksmode.org/js/keys.html