Javascript绑定keyup / down事件 [英] Javascript bind keyup/down event

查看:92
本文介绍了Javascript绑定keyup / down事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I bind a function to the key down/up events?

它可以绑定到整个文档或单个元素,也可以在这种情况。

It can be either binded to the entire document or a single element, either will work in this case.

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

This has to be without any JavaScript library. I am only primarily concerned with the latest Firefox. Particularly the canvas element.

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

Ive tried this: (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>


推荐答案

关键事件仅触发可能的文档和元素得到关注。因此,要处理< canvas> 元素上的关键事件,您需要通过添加 tabindex 属性(例如< canvas id =gamewidth =800height =400tabindex =1>< / canvas> )或只需处理整个文档的关键事件,这可能不是您想要的(例如,如果您希望处理关键事件的页面上有多个元素)。

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);
};

如果您可能需要多个监听器,可以使用 addEventListener 或IE中的 attachEvent < = 8:

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);
    });
}

这篇关于Javascript绑定keyup / down事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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