javascript keydown 事件仅适用于 html 输入标签?

标签 javascript input keydown

我使用keyDown事件通过判断e.keycode来管理输入标签值, 但是当我想使用 keyDown 事件在 body 元素或 img 上执行某些操作时, 我发现它不起作用,例如:

$('body,img').keyDown(function(e){
    console.log(e.keyCode);
});

keyDown 事件仅适用于 input 标记吗?

最佳答案

keyDown 事件仅适用于可聚焦元素。这将包括输入字段、文本区域等,但您可能找不到任何支持 img 元素的浏览器。来自 jQuery docs :

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

您可能也对此相关问题感兴趣:Which HTML elements can receive focus?

关于javascript keydown 事件仅适用于 html 输入标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10394912/

相关文章:

c# - C# 中的新手 MVVM 尝试使用 Esc 关闭应用程序(处理键命令)

macos - 响应 keyDown 事件的最佳实践

javascript - 在日期选择器插件中隐藏其他月份的日期?

javascript - 使用 Backfire 绑定(bind)对模型执行提取不会检索任何数据

css - HTML 输入,没有焦点的闪烁插入符?

javascript - 通过添加第一个和第二个字段的值,自动将值添加到第三个字段

c - 将按钮的寄存器标记为已读

javascript - 获取所有输入类型的密码

javascript - 如何为电子邮件编写一个正则表达式,它将找到开头和空格,无论电子邮件是否存在?

c# - Visual C# 读取 RFID 卡时按键检测异常(添加 D 字符)