I'm attempting to capture arrow key presses in jQuery, but no events are being triggered.

$(function(){
    $('html').keypress(function(e){
        console.log(e);
    });
});

This generates events for alphanumeric keys, but delete, arrow keys, etc generate no event.

What am I doing wrong to not be capturing those?

推荐答案

You should use .keydown() because .keypress() will ignore "Arrows", for catching the key type use e.which

Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.

Notes:

  1. .keypress()永远不会用Shift、Esc和Delete键触发,但.keydown()会.
  2. 实际上,在某些浏览器中,.keypress()会被箭头键触发,但它不是跨浏览器的,所以使用.keydown()更可靠.

More useful information

  1. You can use .which Or .keyCode of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which never had a problem with).
  2. To detect a ctrl | alt | shift | META press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
  3. Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):

    • Enter: 13
    • 上升:38
    • Down: 40
    • 右:39
    • 左:37
    • Esc: 27
    • SpaceBar: 32
    • Ctrl: 17
    • Alt: 18
    • Shift: 16

Jquery相关问答推荐

如何在for循环期间上传文件

在 Bootstrap 3 中向工具提示添加换行符

jQuery ajax() 使用成功、错误和完成与 .done()、.fail() 和 always()

这些 jQuery 就绪函数之间有什么区别?

Google Maps API v3 infowindow 关闭事件/回调?

调用 jquery ajax - .fail vs. :error

将输入更改为大写

使用 JavaScript 和 jQuery,跨浏览器处理按键事件 (F1-F12)

将 CSS 应用于 jQuery 对话框按钮

如何在 Angular 4 中使用 jQuery 插件?

页面重新加载后,如何使用 twitter bootstrap 保持当前选项卡处于活动状态?

如何隐藏 Twitter Bootstrap 下拉菜单

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

你能在不影响历史的情况下使用哈希导航吗?

使用 jQuery Select 空文本输入

默认情况下如何将tinymce粘贴为纯文本

D3 和​​ jQuery 有什么区别?

如何在 DOM 中移动 iFrame 而不会丢失其状态?

使用 jQuery 检测元素内容的变化

jQuery 将换行符转换为 br (nl2br 等效)