通过javascript / jQuery检测IE中的箭头按键 [英] Detecting Arrow key press in IE via javascript/jQuery

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

问题描述

我正在尝试设置一个可以通过箭头键导航的菜单。我在Firefox中有这个工作片。

I'm trying to set up a menu that can be navigated via the arrow keys. I have this working fin in Firefox.

试图让它在IE8中工作并经过一些努力,发现这是因为IE8不会注册一个按键在箭头上。测试:

Trying to get it to work in IE8 and after a bit of struggle, found that it was because IE8 wouldn't register a keypress on the arrows. To test:

$(document).keypress(function (eh){ 
    alert(eh.keyCode);
};

在Firefox中,按任意箭头键会触发37的警报,38,39或40。

In Firefox, pressing any of the arrow keys would trigger an alert of 37, 38, 39 or 40.

在IE8中,没有。标准QWERTY键盘上的任何其他键都会注册,但不会注册箭头键。

In IE8, nothing. Any other key on the standard QWERTY keyboard would register, but not the arrow keys.

这是我的Javascript问题吗?浏览器设置?Windows设置?

Is this an issue with my Javascript? A browser setting? A Windows setting?

推荐答案

来自 jQuery keypress 文档(最后一段)介绍性文字):

From the jQuery keypress documentation (the last paragraph of the introductory text):


注意 keydown keyup 提供一个代码,指示按下哪个键,而 keypress 表示输入了哪个字符。例如,将报告一个小写的a 65由 keydown keyup ,但由 keypress 所有事件都报告大写A为97。由于这种区别,当捕获箭头键, .keydown() .keyup()等特殊键击时,一个更好的选择。

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 97 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

它甚至提到了箭头键;)因此,你真的需要挂钩 keydown keyup 事件。这是 SSCCE keydown ,只是copy'n'paste'n '运行。不,您不需要对事件进行浏览器兼容检查,这适用于从IE6到Firefox的所有浏览器。

It even literally mentions about the arrow keys ;) Thus, you really need to hook on either the keydown or keyup events. Here's an SSCCE with keydown, just copy'n'paste'n'run it. No, you don't need to do a browser-compatible check on the event, this works in all browsers from IE6 up to with Firefox.

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2217553</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script>
            $(document).keydown(function(event) {
                switch (event.keyCode) {
                    case 37: alert('left'); break;
                    case 38: alert('up'); break;
                    case 39: alert('right'); break;
                    case 40: alert('down'); break;
                }
            });
        </script>
    </head>
    <body>
       <p>Press one of the arrow keys.</p> 
    </body>
</html>

这篇关于通过javascript / jQuery检测IE中的箭头按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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