我正在尝试设置一个函数,每次单击 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 事件。
- 可以通过多种方式读取 key 。使用
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 脚本中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700798/