我正在尝试设置一个函数,该函数每次单击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>
答案 0 :(得分:2)
您遇到了一些问题。
code
给您一个字符串(就像我添加的一样)。如果要使用数字,请使用event.which
。看看this了解更多详情。}
大括号。
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>
答案 1 :(得分:0)
好吧,因为我不明白您要单击左键或右键或按键盘上的左右箭头键来获取触发器,所以我给出了两种情况的代码:
对于“ 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!");
}
}