javascript prevent scrolling

2019-09-02 20:50发布

问题:

I am trying to prevent scrolling when I use arrow keys in my HTML5 game. It is a maze game that you control with arrow keys or buttons on the screen, but whenever I press the 'up' or 'down' keys, it always scrolls.I am using:

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
    } else if(e.keyCode === 38) {
        up();
    } else if(e.keyCode === 37) {
        leftclick();
    } else if(e.keyCode === 39) {
        rightclick();
    }
})

Is this possible with javascript? I want it to be able to scroll with my mouse, but not when I use arrow keys on my keyboard. My game is at http://thomaswd.com/maze. Please help. Thanks!

回答1:

Use e.preventDefault() to prevent the normal key action from taking place.

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
        e.preventDefault();
    } else if(e.keyCode === 38) {
        up();
        e.preventDefault();
    } else if(e.keyCode === 37) {
        leftclick();
        e.preventDefault();
    } else if(e.keyCode === 39) {
        rightclick();
        e.preventDefault();
    }

})



回答2:

Try this:

document.addEventListener('keydown', function(e) {
        if(e.keyCode > 36 && e.keyCode < 41) {
            e.preventDefault();
        }
        if (e.keyCode === 40) {
            down();
        } else if (e.keyCode === 38) {
            up();
        } else if (e.keyCode === 37) {
            leftclick();
        } else if (e.keyCode === 39) {
            rightclick();
        }
        return false;
    }, false);
}


回答3:

Try to add e.preventDefault(); at the end