Javascript有没有按键调用函数的方法?

Is there a way to call a function by a key press in Javascript?

有没有办法在按键事件时调用函数。 我的目标是制作一个可移动的方块,我想知道您是否可以调用该函数来移动 <div> 方块。我也有一个关于让角色可见的问题,所以如果能帮我解决这个问题会很有帮助!

JavaScript

//variables
var player = document.getElementById('player');

var character = {
left: player.style.left + 1,
right: player.style.right + 1,
top: player.style.top + 1,
bottom: player.style.bottom + 1,
body: document.createElement('div'),
}


//functions
 function running() {
    console.log("Running");
    console.log("Program running");
    document.appendChild('div');
 }

 function loop() {
    running();
 }

function moveRight() {
    character.style.position = absolute;
    character.style.top = top + "px";
    character.style.right = right + 2 + "px";
}

function moveLeft() {
    character.style.position = absolute;
    character.style.top = top + "px";
    character.style.left = left + 2 + "px";
}

function moveup() {
    character.style.position = absolute;
    character.style.top = top + "px";
    character.style.right = right + 2 + "px";
}



//functions called
 loop();

HTML

<!DOCTYPE html>
<html>
<head>
    <title>RPG</title>
</head>
<body>
    <div id="allCode">
    <script type="text/javascript" src="index.js"></script>
    <style type="text/css" src="style.css"></style>
    </div>
    <div id="player"></div>
</body>
</html> 

也许这可以引导您朝着正确的方向前进。 link 使用箭头键移动对象。

https://www.includehelp.com/code-snippets/move-object-with-arrow-keys-using-javascript-function.aspx

javascript 中有很多关于如何处理键处理事件的示例,这应该可以帮助您入门:

document.addEventListener('keydown', function(event) {
    switch (event.keyCode) {
        case 37:
            //left function
            break;
        case 38:
            //Up function
            break;
        case 39:
            //Right function
            break;
    }
});

编辑:.keyCode.which.charCode 是已弃用的属性: 所以你应该使用 event.key

例如:

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }

  switch (event.key) {
    case "Up": // IE/Edge specific value
    case "ArrowUp":
      //Up function
      break;

    case "Left": // IE/Edge specific
    case "ArrowLeft":
      //left function
      break;

    case "Right": // IE/Edge specific
    case "ArrowRight":
      //Right function
      break;
   
    default:
      return; // No key event
  }

  event.preventDefault(); // Avoid key handling twice
}, true);