在用户浏览器中禁用箭头键滚动 [英] Disable arrow key scrolling in users browser

查看:323
本文介绍了在用户浏览器中禁用箭头键滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用画布和javascript制作游戏。

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 the game impossible to play.

当播放器只想向下移动时,我可以如何防止窗口滚动?

What can I do to prevent the window from scrolling when the player just wants to move down?

我猜Java游戏,这样,这不是一个问题,只要用户点击游戏。

I guess with Java games, and such, this is not a problem, as long as the user clicks on the game.

我尝试了解决方案:如何使用箭头键在FF中禁用页面滚动,但我无法让它工作。

I tried the solution from: how to disable page scrolling in FF with arrow keys ,but I couldn't get it to work.

推荐答案

摘要



只需防止默认的浏览器操作:

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

魔法发生在 e.preventDefault(); 。这将阻止事件的默认操作,在这种情况下移动浏览器的视点。

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

如果你不需要当前的按钮状态,你可以简单地放下 keys ,只需舍弃箭头键上的默认操作:

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



参考




  • MDN: window.addEventListener

  • MDN: window.removeEventListener

  • References

    • MDN: window.addEventListener
    • MDN: window.removeEventListener
    • 这篇关于在用户浏览器中禁用箭头键滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆