为什么触发器箭头键事件在Java Script中不起作用?

我正在尝试设置一个函数,该函数每次单击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>

jzym123 回答:为什么触发器箭头键事件在Java Script中不起作用?

您遇到了一些问题。

  1. 您从未在onkeydown属性上添加结束引号。
  2. 您必须在div上有一个tabindex(并专注于它),才能使其接收按键事件。
  3. 可以通过多种方式读取密钥。使用code给您一个字符串(就像我添加的一样)。如果要使用数字,请使用event.which。看看this了解更多详情。
  4. 您的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>

,

好吧,因为我不明白您要单击左键或右键或按键盘上的左右箭头键来获取触发器,所以我给出了两种情况的代码:

对于“ Pressing”事件,您需要将触发器置于HTML上的元素上

<body onkeydown="arrowFunction(event)">

以及以下JavaScript

function arrowFunction(event) { var x = event.key; if (x == "ArrowLeft") { 
    alert ("You pressed the 'Left' key!");
  }
  if (x == "ArrowRight") { 
    alert ("You pressed the 'Right' key!");
  }
}

对于“点击”事件,您需要创建两个按钮元素并将onClick事件放在它们上

<button onclick="arrowFunction('left')">Left Button</button>
<button onclick="arrowFunction('right')">Right Button</button>

和以下JavaScript

function arrowFunction(event) {
        var x = event;
        if (x == "left") {
          alert("You pressed the 'Left' key!");
        }
        if (x == "right") {
          alert("You pressed the 'Right' key!");
        }
      }
本文链接:https://www.f2er.com/3163850.html

大家都在问