问题
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?
I'm using the following: Local HTML page, Google Chrome, Windows
(FYI - the entire page isn't displayed at one time)
Here is my code:
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;
});
回答1:
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);
来源:https://stackoverflow.com/questions/30447487/html-page-scrolls-on-keydown