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

前端之家收集整理的这篇文章主要介绍了在vanilla Javascript中以编程方式触发keydown事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在keydown上运行的窗口附加了一个事件.我想通过以编程方式命中键盘上的一个例程(每个时间间隔)来测试它.以下代码不起作用 – 但如果我实际按下键盘上的某个键,则可以正常工作.

我最初尝试过:

var evt = document.createEvent("KeyboardEvent");
setInterval(function() {
    evt.initKeyEvent("keydown",true,window,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!");
        }
    }
});

解决方法

我相信
evt.initKeyEvent();

应该是

evt.initKeyboardEvent();
原文链接:https://www.f2er.com/js/157264.html

猜你在找的JavaScript相关文章