我试图设置一个函数,该函数每次在Javascript中单击向右箭头或向左箭头时都会创建警报。



    function arrowFunction(event) {
      var x = event.key;

      // If the pressed keyboard button is "a" or "A" (using caps lock or shift), alert some text.
      if (x == "37") {
        alert ("You pressed the 'left' key!");
      }
    }
      if (x == "38") {
        alert ("You pressed the 'left' key!");
      }
    }

    <p><button onclick="myMove()">Click Me</button></p>

    <div id ="container">
      <div id ="animate" onclick="myMove()" onkeydown="arrowFunction(event) ></div>
    </div>

最佳答案

您遇到了几个问题。


您从未在onkeydown属性上添加结束引号。
您必须在div上有一个tabindex(并专注于它),才能使其接收到keydown事件。
有多种读取密钥的方法。使用code给您一个字符串(就像我添加的一样)。如果要使用数字,请使用event.which。有关更多详细信息,请参见this
您的JS中有一个额外的}大括号。




function arrowFunction(event) {
  var x = event.key;
  console.log(x);
  if (x == "ArrowLeft") {
    alert ("You pressed the 'left' key!");
  }
  // You had an extra slash here
  if (x == "ArrowRight") {
    alert ("You pressed the 'right' key!");
  }
}

function myMove() {}

#animate {
  width: 100px;
  height: 100px;
  background-color: deeppink;
}

Click the box to focus on it...

<div id ="container">
  <!-- You are missing the end quote here. Also need a tabindex -->
  <div id ="animate" onclick="myMove()" onkeydown="arrowFunction(event)" tabindex="0"></div>
</div>

关于javascript - 为什么我的触发箭头键事件在Java Script中不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58700798/

10-12 12:27
查看更多