jQuery - keydown()在div上不起作用 [英] jQuery - keydown() on div not working in Firefox

查看:2056
本文介绍了jQuery - keydown()在div上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例代码,当div处于焦点并按下一个键时,该代码应该弹出警报。这是我在IE 7中所期待的,但在Firefox 3.5.5中却没有。我做错了什么?

I have the following example code, which should pop up an alert when the div is in focus and a key is pressed. This does what I expect in IE 7, but not in Firefox 3.5.5. What am I doing wrong?

<html>
<head>
    <title>JS test</title>
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#testdiv").keydown(function(event) {
                alert("Pressed " + event.keyCode);
            });
        });
    </script>    
    <style type="text/css">
        #testdiv
        {
            width: 50;
            height: 50;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="testdiv"></div>
</body>
</html>

编辑:我刚刚尝试替换 keydown keypress keyup ,那些也不起作用。顺便说一下,我也确保我的找到你输入设置被关闭,以防万一。

EDIT: I've just tried replacing keydown with keypress and keyup and those don't work either. Incidentally, I also made sure that my "Find as you type" setting is turned off just in case.

推荐答案

你需要给div一个tabindex,以便它可以得到焦点。

You need to give the div a tabindex so it can receive focus.

<div id="testdiv" tabindex="0"></div>

这篇关于jQuery - keydown()在div上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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