javascript prevent scrolling

2019-09-02 20:34发布

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!

3条回答
趁早两清
2楼-- · 2019-09-02 21:14

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楼-- · 2019-09-02 21:16

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();
    }

})

查看更多
爷、活的狠高调
4楼-- · 2019-09-02 21:19

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

查看更多
登录 后发表回答