Disable arrow key scrolling in users browser

后端 未结 3 1106
盖世英雄少女心
盖世英雄少女心 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:20

    I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
    Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

    In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

    window.addEventListener('keydown', (e) => {
        if (e.target.localName != 'input') {   // if you need to filter  elements
            switch (e.keyCode) {
                case 37: // left
                case 39: // right
                    e.preventDefault();
                    break;
                case 38: // up
                case 40: // down
                    e.preventDefault();
                    break;
                default:
                    break;
            }
        }
    }, {
        capture: true,   // this disables arrow key scrolling in modern Chrome
        passive: false   // this is optional, my code works without it
    });
    

    Quote for EventTarget.addEventListener() from MDN

    options Optional
       An options object specifies characteristics about the event listener. The available options are:

    capture
       A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
    once
       ...
    passive
       A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

提交回复
热议问题