Javascript绑定keyup/down事件

Pet*_*tah 20 javascript javascript-events

如何将函数绑定到按键向下/向上事件?

它既可以绑定到整个文档,也可以绑定到单个元素,在这种情况下都可以使用.

这必须没有任何JavaScript库.我只关心最新的Firefox.特别是画布元素.

我试过这个:(FF 3.6.9 Windows 7)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <div class="wrapper">
            <canvas id="game" width="800" height="400">
            </canvas>
        </div>
        <script type="text/javascript">
            var el = document.getElementById("game");

            el.onkeydown = function(evt) {
                evt = evt || window.event;
                alert("keydown: " + evt.keyCode);
            };

            el.onkeyup = function(evt) {
                evt = evt || window.event;
                alert("keyup: " + evt.keyCode);
            };
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Tim*_*own 40

Key events only fire on the document and elements that may receive focus. Therefore to handle key events on a <canvas> element, you either need to allow it to receive focus by adding a tabindex attribute (e.g. <canvas id="game" width="800" height="400" tabindex="1"></canvas>) or by simply handling key events for the whole document, which may not be what you want (for example, if you have more than one element on the page for which you wish to handle key events).

As to how to attach the event handlers, the simplest way is the following:

var el = document.getElementById("your_element_id");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    alert("keydown: " + evt.keyCode);
};

el.onkeyup = function(evt) {
    evt = evt || window.event;
    alert("keyup: " + evt.keyCode);
};
Run Code Online (Sandbox Code Playgroud)

If you may need multiple listeners, you can use addEventListener in most browsers or attachEvent in IE <= 8:

if (typeof el.addEventListener != "undefined") {
    el.addEventListener("keydown", function(evt) {
        alert("keydown: " + evt.keyCode);
    }, false);
} else if (typeof el.attachEvent != "undefined") {
    el.attachEvent("onkeydown", function(evt) {
        alert("keydown: " + evt.keyCode);
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 那是因为`<canvas>`元素默认不能接收焦点.您有两种选择:要么可以在canvas标记中添加`tabindex`属性以允许它获得焦点,要么可以将键事件处理程序附加到`document`. (4认同)