使用onkeypress检测被按下的箭头(HTML和Javascript)

时间:2012-11-10 14:31:06

标签: javascript html javascript-events

我一直在尝试编写没有Jquery的乒乓球游戏(来自软件设计老师的挑战),并且正计划使用onkeypress来移动拨片。但是,我不确定如何将特定键附加到事件处理程序中指定的函数。

这不是非常相关,但这是我的代码:

HTML:

<div id="Paddle1" class="paddle" onkeypress="PaddleMovement1(event)"></div>
<div id="Paddle2" class="paddle" onkeypress="PaddleMovement3(event)"></div>

使用Javascript:

var PaddleMovement1 = function(){
    document.getElementById('Paddle1Up').style.animationPlayState="running";
    setTimeout(Paddle1Stop1, 25)
    var Paddle1Stop1 = function(){
        document.getElementById('Paddle1Up').style.animationPlayState="paused";
    };
};

var PaddleMovement2 = function(){
    document.getElementById('Paddle1Down').style.animationPlayState="running";
    setTimeout(Paddle1Stop2, 25)
    var Paddle1Stop2 = function(){
        document.getElementById('Paddle1Down').style.animationPlayState="paused";
    };
};

var PaddleMovement3 = function(){
    document.getElementById('Paddle2Up').style.animationPlayState="running";
    setTimeout(Paddle2Stop1, 25)
    var Paddle2Stop1 = function(){
        document.getElementById('Paddle2Up').style.animationPlayState="paused";
    };
};

var PaddleMovement4 = function(){
    document.getElementById('Paddle2Down').style.animationPlayState="running";
    setTimeout(Paddle2Stop2, 25)
    var Paddle2Stop2 = function(){
        document.getElementById('Paddle2Down').style.animationPlayState="paused";
    };
};

最后,完整的东西可以在这个jsfiddle中找到:

http://jsfiddle.net/2RfzF/2/

1 个答案:

答案 0 :(得分:2)

keypress仅针对导致可输入字符而非其他键的按键触发。要检测其他密钥,请使用keydownkeyup。从the specification

开始,这一点应该相当清楚
  

用户代理必须在按下某个键时调度此事件,当且仅当该键通常产生字符值时。

This page是一个方便的指南,可以解决JavaScript浏览器中的键盘事件......

另外,出于您的目的,我可能会将事件记录在document而不是特定元素(keydownkeyup气泡上,这样就可以了。

例如:

(function() {
    if (document.addEventListener) {
        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keydown", keyUpHandler, false);
    }
    else if (document.attachEvent) {
        document.attachEvent("onkeydown", function() {
            keyDownHandler(window.event);
        });
        document.attachEvent("onkeydown", function() {
            keyUpHandler(window.event);
        });
    }
    else {
        // If you want to support TRULY antiquated browsers
        document.onkeydown = function(event) {
            keyDownHandler(event || window.event);
        };
        document.onkeyup   = function(event) {
            keyUpHandler(event || window.event);
        };
    }

    function keyDownHandler(e) {
        var key = e.which || e.keyCode;
        display("keydown: " + key);
    }

    function keyDownHandler(e) {
        var key = e.which || e.keyCode;
        display("keyup: " + key);
    }

    function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
    }
})();

Live Copy | Source