jQuery Keypress箭头键 [英] jQuery Keypress Arrow Keys

查看:143
本文介绍了jQuery Keypress箭头键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获jQuery中的箭头按键,但没有触发任何事件。

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?

推荐答案

这是例如: JSnippet DEMO keydown()vs keypress()

你应该使用 .keydown()因为 .keypress()将忽略箭头,用于捕捉密钥类型使用 e.which

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.

注意:


  1. .keypress()永远不会使用Shift,Esc和Delete触发,但。 keydown()将。

  2. 实际上 .keypress()在某些浏览器中将由箭头键触发但它不是跨浏览器所以它的mo可靠使用 .keydown()

  1. .keypress() will never be fired with Shift, Esc, and Delete but .keydown() will.
  2. Actually .keypress() in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown().

更有用信息


  1. 您可以使用 .which 或者事件对象的 .keyCode - 有些浏览器不支持其中一个,但是当使用jQuery时,可以安全地使用它们,因为jQuery标准化了东西。 (我更喜欢 .which 从未出现问题)。

  2. 要检测 ctrl | alt |转移| META 按下实际捕获的键,您应该检查事件对象的以下属性 - 如果按下它们将被设置为TRUE:


    • event.ctrlKey - ctrl

    • event.altKey - alt

    • event.shiftKey - shift

    • event.metaKey - META(命令⌘或Windows键

  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:
    • event.ctrlKey - ctrl
    • event.altKey - alt
    • event.shiftKey - shift
    • event.metaKey - META ( Command ⌘ OR Windows Key )

最后 - 这是一些有用的密钥代码(有关完整列表 - keycode-cheatsheet ):

Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):


  • 输入:13

  • Up:38

  • 羽绒:40

  • 右:39

  • 左:37

  • Esc:27

  • SpaceBar:32

  • Ctrl:17

  • Alt:18

  • Shift:16

  • Enter: 13
  • Up: 38
  • Down: 40
  • Right: 39
  • Left: 37
  • Esc: 27
  • SpaceBar: 32
  • Ctrl: 17
  • Alt: 18
  • Shift: 16

这篇关于jQuery Keypress箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆