在KeyboardEvent中,应该使用哪个属性来确定按下哪个键?

时间:2017-03-02 23:17:53

标签: javascript keyboard-events

e.g。按键事件将返回以下

KeyboardEvent {
    charCode: 32,
    code: "Space",
    key: " ", // space character
    keyCode: 32,
    which: 32
}

哪些(如果有的话)已弃用/不应使用?代码对我有意义,因为它是人类可读的。 Afaik,which已被弃用。

3 个答案:

答案 0 :(得分:2)

I just did some research... According to mdn (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) we should use key "If available".

char is deprecated

charCode is deprecated

keyCode is deprecated

which is deprecated

code is not deprecated, so I assume we use this if key is not available.

答案 1 :(得分:1)

I'm looking in the debugger and tracing out an event object in Angular 2. You would clearly use keyCode. I'm pretty sure that's what the docs say too. Interested where this conversation goes. However note I use keyCode and get exactly what I need from all keys (enter shift etc).

It makes sense I guess; you want the key, use the keycode. You want the character, use charCode. You might intuit them as the same but it would seem they're not (or at least, not always).

Just to add all the detail, I'm bound to the keyup event. It's probably not angular 2 specific but just sharing environment etc.

答案 2 :(得分:0)

keyCode确定按下了哪个键。除keyCode包括shiftKeyaltKeyctrlKeymetaKey以检测特殊键。< / p>