javascript - 为什么我的触发箭头键事件在 Java 脚本中不起作用?

标签 javascript html events

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

最佳答案

您遇到了几个问题。

  1. 您从未在 onkeydown 属性上添加结束引号。
  2. 您必须在 div 上有一个 tabindex(并关注它)才能接收 keydown 事件。
  3. 可以通过多种方式读取 key 。使用 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>

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

相关文章:

javascript - 根据文本框的值创建文本框

javascript - 如何让跨多个文件的多个 JavaScript 对象访问同一个私有(private)变量?

javascript - 如何从另一个页面 html 打开 Bootstrap 模式?

javascript - jQuery UI 对话框问题

c# - 有没有办法在没有 Canvas 的浏览器中用javascript绘制简单的形状?

javascript - 在 gulp 中注入(inject) js 和 css 时,如何提供对 index.html 的写权限?

javascript - 单击图像时将 div 显示为弹出窗口

c# - 每当属性的值发生变化时引发事件?

javascript - Colorthief.js 与 Polymer.js - 查找导致 onload 事件的图像的原色

java - 如何在 Java 中使用 TwoTuple 集合设置变量?