一些桌面应用程序以不同方式处理“回车”键和小键盘的“输入”键。我注意到这两个键在 Javascript (jQuery) 中生成相同的 keyCode (13)。
它们在浏览器环境中是否转换为相等,或者是否可以区分它们(即让 CR 在文本区域换行,然后按“回车”键提交表单?
最佳答案
参见 Jan Wolters 关于 Javascript Madness: Keyboard Events 的论文.
Enter
和 Numpad Enter
都提供相同的键码,即 13,因为浏览器不区分这两个键。老实说,大多数环境也不行。可以使用 Windows API(例如)区分它们,但这样做确实需要额外的努力。然而,这超出了浏览器的抽象范围。
更新
作为 Bill Thorne 理所当然 mentions , KeyboardEvent
对象如今拥有一个 location
属性。
Possible values are:
DOM_KEY_LOCATION_STANDARD
0
The key has only one version, or can't be distinguished between the left and right versions of the key, and was not pressed on the numeric keypad or a key that is considered to be part of the keypad.
DOM_KEY_LOCATION_LEFT
1
The key was the left-hand version of the key; for example, the left-hand Control key was pressed on a standard 101 key US keyboard. This value is only used for keys that have more that one possible location on the keyboard.
DOM_KEY_LOCATION_RIGHT
2
The key was the right-hand version of the key; for example, the right-hand Control key is pressed on a standard 101 key US keyboard. This value is only used for keys that have more that one possible location on the keyboard.
DOM_KEY_LOCATION_NUMPAD
3
The key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad.Note: When NumLock is locked, Gecko always returns DOM_KEY_LOCATION_NUMPAD for the keys on the numeric pad. Otherwise, when NumLock is unlocked and the keyboard actually has a numeric keypad, Gecko always returns DOM_KEY_LOCATION_NUMPAD too. On the other hand, if the keyboard doesn't have a keypad, such as on a notebook computer, some keys become Numpad only when NumLock is locked. When such keys fires key events, the location attribute value depends on the key. That is, it must not be DOM_KEY_LOCATION_NUMPAD. Note: NumLock key's key events indicate DOM_KEY_LOCATION_STANDARD both on Gecko and Internet Explorer.
关于javascript - 如何区分 Javascript 中的 'Enter' 和 'Return' 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5418313/