Javascript HTML 元素上的 onkeydown 事件

Javascript onkeydown event on HTML element

我正在尝试制作一个使用 WASD 移动 WebGL (three.js) 相机的应用程序。但是,当我使用

onkeydown = function(e) { alert("a") }

并尝试在同一页面上的文本框中键入内容,它会触发侦听器。我将代码更改为如下所示:

var container = document.getElementById("container");
container.onkeydown = function(e) { alert("a") }

但这没有用,因为 HTML 内容还没有加载,所以,我添加了 jQuery:

var container;
$(function() {
  container = document.getElementById("container");
  container.onkeydown = function(e) { alert("a") }
});

现在,侦听器根本不起作用,是否可以使它起作用?

为了让它工作,你的元素必须是 focused:

When an element is focused, key events received by the document must be targeted at that element. There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element

但是,为了能够聚焦元素,它必须是focusable:

An element is focusable if all of the following conditions are met:

通常,问题是缺少tabindex 焦点标志。您可以通过添加具有整数值的 tabindex attribute 来设置它。

一旦元素可聚焦,您就需要聚焦它。有多种方法可以做到这一点,例如

  • 使用JavaScript,使用.focus()方法。
  • 用鼠标点击它(不取消mousedown事件)
  • 按 Tab 键浏览可聚焦的元素。如果您使用非负数 tabindex,该元素最终将成为焦点。

例如:

var container = document.getElementById("container");
container.onkeydown = function(e) { alert("Key detected") }
#container { border: 3px solid red; padding: 10px; }
#container:focus { border-color: green; }
#container:after { content: "Now I'm not focused, so it won't work. Click me."; }
#container:focus:after { content: "Now I'm focused, so it will work. Press a key."; }
<div id="container" tabindex="-1"></div>

您需要使用 DOMContentLoaded 事件来延迟执行,直到 HTML 加载完毕。在普通 JavaScript 中,它看起来像这样:

document.addEventListener('DOMContentLoaded', function() {
    var container = document.getElementById('container');
    container.addEventListener('keydown', function(e) { alert("a") });
});

和jQuery差不多,就是短了一点:

$(document).ready(function() {
    var container = document.getElementById('container');
    $(container).keydown(function(e) { alert("a") });
});

(加上 Oriol 所说的 tabindex。)

function myFunction() {
  alert("a");
}
<body>
  <table>
     <tr>
        <td>
           <input  type="text"  name="container" id="container" value=""  onkeydown="myFunction()">
       </td>
     </tr>
  </table>
</body>