Is it OK to ignore keydown events with keyCode = 229?

旧巷老猫 提交于 2019-11-30 05:13:58

The short answer is No. You can ignore keydown events with keyCode = 229, but only if they follow immediately after a keypress event.

If you hold certain keys down, some browsers send a repeated keydown event with a keyCode value of 229, while others send the original keydown keyCode again. Some browsers send 0 as the keyCode associated with the keypress event, and place the character code in a charCode property.

In all cases, as far as I can tell from my tests, the order of events is always predictable:

keydown  (event.keyCode  = key-keyCode            ex: 65 = "A")
keypress (event.keyCode  = 0 | character-keyCode  ex: 97 = "a")  - conflated model
          event.charCode =     character-keyCode                 - split model
keydown  (event.keyCode  = 229 | key-keyCode      ex: 229 | 65)  - may be repeated
keyup    (event.keyCode  = key-keyCode            ex: 65)

The letter å is used in a number of Scandinavian languages. Here are the events received in Safari 6.1.5 when the keyboard is set to Swedish or Finnish, and the å character (to the left of the P key) is pressed:

EVENT    keyCode
keydown  219     ("[" key position)
keypress 229     (å)
keydown  229     (repeatedly, indicating that the Input Monitor is busy)
keyup    219

Notice that the initial keydown keyCode is 219, not 229.

To generate a 229 keyCode on the initial keydown event, you can press any "dead key". On the Swedish keyboard on Mac, for example, the key immediately to the left of of the BACKSPACE key is ´ (acute accent), as used in words like déjà-vu. When you press a dead key, the character appears in the input field, but the insertion point does not move. When you subsequently type a character that can be combined with it, the browser may replace the initial dead key character with a composite character (´ + e = é) which has its own Unicode value.

Here are the events that you will see in Safari 6.1.5 when the user presses and releases ´ followed by e on a Swedish keyboard:

EVENT    keyCode
keydown  229 (dead key)
keyup    187 (acute accent)
keydown  229 (second key is being treated)
keyup     69 ("E")

Note that there are no keypress events sent at all, because there is no "é" key as such which has been pressed. If you want to determine which character the user entered, you can wait until after the second keyup, then read the character from the input field.

In other words, you can ignore any keydown events with a 229 keyCode after a keypress event, but if you ignore all 229 keyCodes, you may prevent users from adding various diacritical characters.

For more information on keyCode 229, from the w3.org site: keyCode property of key events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!