移动精灵(Moving a sprite)

我只是希望能够使用W,A,S,D键移动精灵“kitty”。 因此,当我加载页面并按下键时,小猫图片不会移动,我无法弄清楚我做错了什么。 谁能帮助我指出正确的方向?

我的代码:

<!DOCTYPE html> <html> <head> <title>Project 3</title> <style> div.box{ width: 600px; height: 400px; border: 5px solid black; margin: auto; position: relative; } </style> </head> <body onLoad ="position" onKeyDown = "move(event)"> <script> var dx = 5; var dy = 5; var xPos = 0; var yPos = 0; function position() { kitty = document.getElementById("sprite"); kitty.style.left = xPos+"px"; kitty.style.top = yPos+"px"; setTimeout("position()",10); } function move(event) { var keyPressed = String.fromCharCode(event.keyCode); if (keyPressed == "W") { xPos -= dx; } else if (keyPressed == "D") { xPos += dx; } else if (keyPressed == "S") { yPos -= dy; } else if (keyPressed == "A") { yPos += dy; } } </script> <div class="box"> <img src="sprite.jpg" alt="kitty" id="sprite" width="70px" style="position: absolute; left: 0px; top: 0px;"> </div> </body> </html>

I simply want to be able to move the the sprite "kitty" using the keys W,A,S,D. So when i load the page and press the keys the kitty picture does not move and i can't figure out what i'm doing wrong. Can anyone help point me in the right direction?

my code:

<!DOCTYPE html> <html> <head> <title>Project 3</title> <style> div.box{ width: 600px; height: 400px; border: 5px solid black; margin: auto; position: relative; } </style> </head> <body onLoad ="position" onKeyDown = "move(event)"> <script> var dx = 5; var dy = 5; var xPos = 0; var yPos = 0; function position() { kitty = document.getElementById("sprite"); kitty.style.left = xPos+"px"; kitty.style.top = yPos+"px"; setTimeout("position()",10); } function move(event) { var keyPressed = String.fromCharCode(event.keyCode); if (keyPressed == "W") { xPos -= dx; } else if (keyPressed == "D") { xPos += dx; } else if (keyPressed == "S") { yPos -= dy; } else if (keyPressed == "A") { yPos += dy; } } </script> <div class="box"> <img src="sprite.jpg" alt="kitty" id="sprite" width="70px" style="position: absolute; left: 0px; top: 0px;"> </div> </body> </html>

最满意答案

从不调用position函数。 你错过了代码中的parantheses:

onLoad="position()"

The position function is never called. You are missing the parantheses in the code:

onLoad="position()"

更多推荐