KeyboardEvent.keyCode deprecated. What does this mean in practice?

前端 未结 6 1116
甜味超标
甜味超标 2020-12-23 02:36

According to MDN, we should most definitely not be using the .keyCode property. It is deprecated:

https://developer.mozilla.org/en-US/do

6条回答
  •  滥情空心
    2020-12-23 03:05

    TLDR: I'd suggest that you should use the new event.key and event.code properties instead of the legacy ones. IE and Edge have support for these properties, but don't support the new key names yet. For them, there is a small polyfill which makes them output the standard key/code names:

    https://github.com/shvaikalesh/shim-keyboard-event-key


    I came to this question searching for the reason of the same MDN warning as OP. After searching some more, the issue with keyCode becomes more clear:

    The problem with using keyCode is that non-English keyboards can produce different outputs and even keyboards with different layouts can produce inconsistent results. Plus, there was the case of

    If you read the W3C spec: https://www.w3.org/TR/uievents/#interface-keyboardevent

    In practice, keyCode and charCode are inconsistent across platforms and even the same implementation on different operating systems or using different localizations.

    It goes into some depth describing what was wrong with keyCode: https://www.w3.org/TR/uievents/#legacy-key-attributes

    These features were never formally specified and the current browser implementations vary in significant ways. The large amount of legacy content, including script libraries, that relies upon detecting the user agent and acting accordingly means that any attempt to formalize these legacy attributes and events would risk breaking as much content as it would fix or enable. Additionally, these attributes are not suitable for international usage, nor do they address accessibility concerns.

    So, after establishing the reason why the legacy keyCode was replaced, let's look at what you need to do today:

    1. All modern browsers support the new properties (key and code).
    2. IE and Edge support an older version of the spec, which has different names for some keys. You can use a shim for it: https://github.com/shvaikalesh/shim-keyboard-event-key (or roll your own - it's rather small anyways)
    3. Edge has fixed this bug in the latest release (probably will be released in Apr 2018) - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
    4. Refer to the list of event keys you can use: https://www.w3.org/TR/uievents-key/

提交回复
热议问题