Disable arrow key scrolling in users browser

后端 未结 3 1108
盖世英雄少女心
盖世英雄少女心 2020-11-29 20:46

I\'m making a game using canvas, and javascript.

When the page is longer than the screen (comments, etc.) pressing the down arrow scrolls the page down, and makes th

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 21:32

    Summary

    Simply prevent the default browser action:

    window.addEventListener("keydown", function(e) {
        // space and arrow keys
        if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
            e.preventDefault();
        }
    }, false);
    

    Original answer

    I used the following function in my own game:

    var keys = {};
    window.addEventListener("keydown",
        function(e){
            keys[e.keyCode] = true;
            switch(e.keyCode){
                case 37: case 39: case 38:  case 40: // Arrow keys
                case 32: e.preventDefault(); break; // Space
                default: break; // do not block other keys
            }
        },
    false);
    window.addEventListener('keyup',
        function(e){
            keys[e.keyCode] = false;
        },
    false);
    

    The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

    If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

    var arrow_keys_handler = function(e) {
        switch(e.keyCode){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    };
    window.addEventListener("keydown", arrow_keys_handler, false);
    

    Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

    window.removeEventListener("keydown", arrow_keys_handler, false);
    

    References

    • MDN: window.addEventListener
    • MDN: window.removeEventListener

提交回复
热议问题