在vanilla Javascript中以编程方式触发keydown事件

时间:2013-08-12 15:27:23

标签: javascript events keydown

我在keydown上运行的窗口附加了一个事件。我想通过以编程方式命中键盘上的一个例程(每个时间间隔)来测试它。以下代码不起作用 - 但如果我实际按下键盘上的某个键,则可以正常工作。

我最初尝试过:

var evt = document.createEvent("KeyboardEvent"); 
setInterval(function() {
    evt.initKeyEvent("keydown", true, true, window, false, false, false, false, 13, 13);
}, 500);

这是我当前的keydown事件:

window.addEventListener('keydown', function(k) {
    switch(k.keyCode) {
        case 38: //up
            if (Game.Area[Game.Player.x][Game.Player.y-1].type !== 0 && Game.Player.y > 0) {
                Game.Player.y--;
            }
            Game.Player.d = 0;
            break;
        case 40: //down
            if (Game.Area[Game.Player.x][Game.Player.y+1].type !== 0 && Game.Player.y < Game.Area[0].length-1) {
                Game.Player.y++;
            }
            Game.Player.d = 1;
            break;
        case 37: //left
            if (Game.Area[Game.Player.x-1][Game.Player.y].type !== 0 && Game.Player.x > 0) {
                Game.Player.x--;
            }
            Game.Player.d = 2;
            break;
        case 39: //right
            if (Game.Area[Game.Player.x+1][Game.Player.y].type !== 0 && Game.Player.y < Game.Area.length-1) {
                Game.Player.x++;
            }
            Game.Player.d = 3;
            break;
        case 66:
            if (Game.Player.d === 0 && Game.Player.y > 0) { //up
                Game.Area[Game.Player.x][Game.Player.y-1].type = 60;
            } else if (Game.Player.d === 1 && Game.Player.y < Game.Area.length) { //down
                Game.Area[Game.Player.x][Game.Player.y+1].type = 60;
            } else if (Game.Player.d === 2 && Game.Player.x > 0) { //left
                Game.Area[Game.Player.x-1][Game.Player.y].type = 60;
            } else if (Game.Player.d === 3 && Game.Player.x < Game.Area.length) { //right
                Game.Area[Game.Player.x+1][Game.Player.y].type = 60;
            }
            break;
        default:
            break;
    }
    Game.MoveZeds();

    for (var z = 0; z < Game.Zeds.length; z++) {
        if (Game.Player.x === Game.Zeds[z].x && Game.Player.y === Game.Zeds[z].y) {
            alert("Ouch!");
        }
    }
});

1 个答案:

答案 0 :(得分:0)

我相信

evt.initKeyEvent();

实际应该是

evt.initKeyboardEvent();