Alternative for event's deprecated KeyboardEvent.which property

后端 未结 3 588
抹茶落季
抹茶落季 2021-02-04 03:25

MDN states that KeyboardEvent.which is deprecated. How can I substitute it for a non-deprecated version?

For example, I have the following:

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 03:47

    From the specification:

    which of type unsigned long, readonly

    which holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. In most cases, the value is identical to keyCode

    keyCode of type unsigned long, readonly

    keyCode holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. Unlike the KeyboardEvent.key attribute, the set of possible values are not normatively defined in this specification. Typically, these value of the keyCode should represent the decimal codepoint in ASCII [RFC20][US-ASCII] or Windows 1252 [WIN1252], but may be drawn from a different appropriate character set. Implementations that are unable to identify a key use the key value '0'.

    See Legacy key models for more details on how to determine the values for keyCode.

    (I have omitted the links)

    So it is quite easy to create a version that is compatible with the specification. The easiest version just returns 0 for each key.

    A slightly more involved version takes event.key and grabs it's ASCII number. You can do the same for the control keys (altKey, ctrlKey, shiftKey).

    In short, as it stands the behavior of which is different between systems and browsers. Using the non-deprecated event information you can create a more robust version that removes these differences and will be more future proof.

    You can check the behavior of your version with the implementation of which in major browsers. If you are not using any edge cases your version will be both simple and compatible.

提交回复
热议问题