In Javascript, how do I tell if a user is pressing two keys at the same time?

前端 未结 4 1930
轻奢々
轻奢々 2021-02-09 13:30

In Javascript, how do I tell if a user is pressing two keys at the same time?

For example, I have drawn a circle in the middle of the screen. I want to move it up while

4条回答
  •  隐瞒了意图╮
    2021-02-09 14:10

    Javascript has onkeydown, and onkeyup events. You can simple fiddle a bit onkeydown for left arrow, and fiddle another bit for the up arrow. On keyup, fiddle the respective bit back.

    var leftPressed,
        upPressed,
        rightPressed,
        downPressed;
    
    var milli = 100;
    
    window.addEventListener('onkeydown', function(e) {
        switch(e.keycode) {
            case 37: //left
                leftPressed = true;
            case 38: //up
                upPressed = true;
            case 39: //right
               rightPressed = true;
            case 40: //down
                downPressed = true;
            default:
                break;
        }
    });
    
    window.addEventListener('onkeyup', function(e) {
        switch(e.keycode) {
            case 37: //left
                leftPressed = false;
            case 38: //up
                upPressed = false;
            case 39: //right
               rightPressed = false;
            case 40: //down
                downPressed = false;
            default:
                break;
        }
    
    });
    
    function moveCircle() {
        if(leftPressed && !rightPressed) {
            // move left
        }
        if(rightPressed && !leftPressed) {
            // move right
        }
        if(upPressed && !downPressed) {
            // move up
        }
        if(downPressed && !upPressed) {
            // move down
        }
    }
    
    setInterval(moveCircle, milli);
    

提交回复
热议问题