jQuery - keydown() on div not working in Firefox

守給你的承諾、 提交于 2019-11-30 01:19:05

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

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

I got the above to work in Firefox, like this:

$('#domainTableDiv').keydown(function(e) {
        alert(e.type + " button(" + e.which + ") ctrl(" + e.metaKey + ") alt(" + e.altKey + ") shift(" + e.shiftKey + ")" );
    });

$('#domainTableDiv').focus();

Once the DIV has focus set on it explicitly, key events fire just fine in Firefox 4.0.1

I don't expect this will work since a div is not something that should receive key events like that. If you placed an <input> inside of that div, and the user pressed a key in the input itself, the event will bubble up to the div and run your function. I'm not 100% sure of what your project is doing so I don't know how to give you more advice, but even though I shouldn't be, I'm kind of surprised that IE is firing off a keydown event on a div.

Avinash

We can also use something like this:

$('#tbl tbody').attr("tabindex", 1).focus();
$('#tbl tbody').keydown(function (event) {
    ...
});
Prem Kumar Maurya

You can check online from here

Source Code

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

I couldn't get any of these answers to work in Firefox 5 using the latest CDN from jquery. I needed to know if one of the children of the div had key events so I resorted to this:

$(document).keypress(function(e){
    if(!$(e.target).parents().is("#testdiv")) return;
    /* do child-of-div specific code here */
}

If the target is the current div (and it has focus), i'd imagine you could do something like this:

$(document).keypress(function(e){
    if(!$(e.target).is("#testdiv")) return;
    /* do div specific code here */
}
Sandman

It is because of the jQuery version. try http://code.jquery.com/jquery-latest.js as source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!