javascript - 如何区分 Javascript 中的 'Enter' 和 'Return' 键?

标签 javascript keycode

一些桌面应用程序以不同方式处理“回车”键和小键盘的“输入”键。我注意到这两个键在 Javascript (jQuery) 中生成相同的 keyCode (13)。

它们在浏览器环境中是否转换为相等,或者是否可以区分它们(即让 CR 在文本区域换行,然后按“回车”键提交表单?

最佳答案

参见 Jan Wolters 关于 Javascript Madness: Keyboard Events 的论文.

EnterNumpad Enter 都提供相同的键码,即 13,因为浏览器不区分这两个键。老实说,大多数环境也不行。可以使用 Windows API(例如)区分它们,但这样做确实需要额外的努力。然而,这超出了浏览器的抽象范围。

更新

作为 Bill Thorne 理所当然 mentions , KeyboardEvent 对象如今拥有一个 location 属性。

来自Mozilla Developer Network :

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/

相关文章:

javascript - 以 MM/DD/YYYY 格式查找下一个最接近的日期 JavaScript

javascript - getBoundingClientRect 检测可见性

javascript - Android 版 Chrome 中的键码始终为零

javascript - 获取键盘数字键中符号的javascript keycode

javascript - 在 JavaScript 中加载游戏关卡,无需后端

javascript - 将 Javascript 代码转换为 php

javascript - 在 jquery 中默认折叠所有选项卡

jquery - 为什么单独用于转义的 keyCode 事件不起作用?

Android - 听数字键盘上的按键?

c++ - 将键码的字符串表示形式转换为 Qt::Key(或任何 int)并返回