42

我有以下示例代码,当 div 处于焦点并按下某个键时,它应该会弹出一个警报。这符合我在 IE 7 中的预期,但在 Firefox 3.5.5 中没有。我究竟做错了什么?

<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>

编辑:我刚刚尝试用 and 替换keydown并且keypress那些keyup也不起作用。顺便说一句,我还确保关闭“键入时查找”设置以防万一。

4

8 回答 8

120

您需要给 div 一个 tabindex 以便它可以接收焦点。

<div id="testdiv" tabindex="0"></div>
于 2009-11-11T21:00:33.403 回答
2

我让上述内容在 Firefox 中工作,如下所示:

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

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

一旦 DIV 明确地将焦点设置在它上面,关键事件就会在 Firefox 4.0.1 中正常触发

于 2011-06-27T18:18:33.140 回答
1

我不希望这会起作用,因为 div 不应该接收这样的关键事件。如果您在该 div 中放置了一个 <input> ,并且用户在输入本身中按下了一个键,则该事件将冒泡到该 div 并运行您的函数。我不是 100% 确定你的项目在做什么,所以我不知道如何给你更多建议,但即使我不应该,我有点惊讶 IE 正在触发 keydown 事件一个分区。

于 2009-11-11T20:53:37.473 回答
1

我们也可以使用这样的东西:

$('#tbl tbody').attr("tabindex", 1).focus();
$('#tbl tbody').keydown(function (event) {
    ...
});
于 2012-12-31T09:28:32.763 回答
1

您可以从这里在线查看

源代码

<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>
于 2013-05-10T15:18:38.850 回答
0

使用来自 jquery 的最新 CDN,我无法在 Firefox 5 中获得任何这些答案。我需要知道 div 的一个孩子是否有关键事件,所以我求助于这个:

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

如果目标是当前的 div (并且它有焦点),我想你可以做这样的事情:

$(document).keypress(function(e){
    if(!$(e.target).is("#testdiv")) return;
    /* do div specific code here */
}
于 2011-06-29T20:24:06.317 回答
0

这是因为 jQuery 版本。尝试http://code.jquery.com/jquery-latest.js作为源

于 2011-09-09T09:19:17.050 回答
0

基本上:

设置 'onkeydown' 事件后调用 yourElement.focus()... 示例

div.onkeydown = (e) {
   alert(e.key)
   // or whatever
}

div.focus() // Add this
于 2022-02-25T11:20:44.980 回答