HTML 页面在 keydown 上滚动 [英] HTML page scrolls on keydown

查看:27
本文介绍了HTML 页面在 keydown 上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏,玩家可以使用箭头键移动,当我点击向上或向下箭头时,屏幕也会移动.有没有办法禁用它?

I have a game in which the player can move using the arrow keys, I when I hit the up or down arrows the screen also moves. Is there a way to disable this?

我正在使用以下内容:本地 HTML 页面、谷歌浏览器、Windows

I'm using the following: Local HTML page, Google Chrome, Windows

(仅供参考 - 整个页面不会一次显示)

(FYI - the entire page isn't displayed at one time)

这是我的代码:

function moveCharacter()
{
    // left arrow
    if (keys[37])
    {
        move("left");
    }
    // up arrow
    if (keys[38])
    {
        move("up");
    }
    // right arrow
    if (keys[39])
    {
        move("right");
    }
    // down arrow
    if (keys[40])
    {
        move("down");
    }
}

document.body.addEventListener("keydown", function(e)
{
    keys[e.keyCode] = true;
    moveCharacter();
});

document.body.addEventListener("keyup", function(e)
{
    keys[e.keyCode] = false;
});

推荐答案

发生这种情况的原因是,在您观察到箭头键按下后,默认操作继续发生 - 滚动屏幕.

The reason this happens is because after you observe the arrow key press, the default action continues to happen - scrolling the screen. The

event.preventDefault()

方法阻止事件的默认操作发生.

method stops the default action of an event from happening.

现在,您只想阻止箭头键的默认操作,不是所有键,否则您将丢失其他键事件或功能,例如在输入字段中键入.下面的代码封装了这个想法.

Now, you only want to prevent the default action of the arrow keys, not all keys, or else you will lose other key events or functions like typing in an input field, for example. The code below encapsulates this idea.

document.addEventListener("keydown", function (e) {
  // Only intercept the arrow keys, not all keys
  if([37,38,39,40].indexOf(e.keyCode) > -1){
    e.preventDefault();

    // Your code
    keys[e.keyCode] = true;
    moveCharacter();
  }
}, false);

这篇关于HTML 页面在 keydown 上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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