我正在为一个我用JavaScript开发的游戏寻找一个KeyListener.我不知道这在实际代码中是如何工作的,但它会是这样的:
if(keyPress == upKey)
{
playerSpriteX += 10;
}
else if(keyPress == downKey)
{
playerSpriteY -= 10;
}
等等…
我搜索了一下,Google提出了涉及AJAX的内容,我还不明白. JavaScript中是否有内置函数可以执行此操作?
解决方法:
这是2019年现代浏览器的更新
let playerSpriteX = 0;
document.addEventListener('keyup', (e) => {
if (e.code === "ArrowUp") playerSpriteX += 10
else if (e.code === "ArrowDown") playerSpriteX -= 10
document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;
});
Click on this window to focus it, and hit keys up and down
<br><br><br>
<div id="test">playerSpriteX = 0</div>
2013年的原始答案
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38) {
playerSpriteX += 10;
}else if (key == 40) {
playerSpriteX -= 10;
}
}