我想将游戏从 onload 更改为 onkeydown(空格),但我不知道如何将整个代码置于 onkeydown 命令下。我是编程爱好者,这是我的第一个项目之一,所以感谢您的帮助:)<body onload="startGame()"><script>function startGame() {myGameArea.start();}var myGameArea = {canvas : document.createElement("canvas"),start : function() { this.canvas.width = 220; this.canvas.height = 400; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]);this.frameNo = 0;updateGameArea(); },clear : function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);} }function component(width, height, color, x, y, type) {this.type = type;function everyinterval(n) { if ((myGameArea.frameNo / n) % 1 == 0) {return true;} return false;}function accelerate(n) { if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);} myGamePiece.gravity = n;}function reload(){ window.location.reload(true);}document.onkeydown = function(event){ if(event.keyCode === 27) paused = !paused;}</script><button onmousedown="accelerate(-0.2); myMusic.play();" onmouseup="accelerate(0.05)">szybuj :')</button>jsFiddle:https ://jsfiddle.net/sidka/k1f4ow0q/6/
1 回答

ITMISS
TA贡献1871条经验 获得超8个赞
而不是onload="startGame()". 将keypress事件添加到您的文档并检查它的keyCode空间 i:e 32。
document.body.addEventListener('keypress', function(e) {
if(e.keyCode == 32) {
startGame();
}
});
document.body.addEventListener('keypress', function(e) {
if(e.keyCode == 32) {
console.log('spacebar');
}
});
<p> Press spacebar </p>
添加回答
举报
0/150
提交
取消