Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="de">
- <head>
- <title>Mario</title>
- <style>
- div {
- position: fixed;
- }
- #meinSpielfeld {
- left: 0;
- top: 0;
- width: 500px;
- height: 500px;
- background-color: black;
- }
- #mario {
- left: 10px;
- top: 400px;
- width: 80px;
- height: 80px;
- background-image: url(http://fluffynukeit.com/wp-content/uploads/2011/06/mario_running.gif);
- }
- </style>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
- </head>
- <body>
- <div id="meinSpielfeld">
- <div id="mario"></div>
- </div>
- <script>
- $(document).ready( function() {
- $("body").keydown(function(e) {
- var aktuellerLeftWert = $("#mario").css("left"); // z.B. "50px"
- // Damit wir rechen können, müssen wir die Endung "px" loswerden
- var aktuellerLeftWertAlsZahl = parseInt(aktuellerLeftWert);
- // Um wieviele Pixel verändern wir die Position?
- var veraenderungDerPosition = 0;
- if (e.keyCode == 37) { // links
- veraenderungDerPosition -= 5;
- } else if (e.keyCode == 39) { // rechts
- veraenderungDerPosition += 5;
- }
- // Ein paar Pixel hinzufügen/abzählen und wieder "px" anhängen
- var neuerLeftWertAlsZahl = aktuellerLeftWertAlsZahl + veraenderungDerPosition
- var neuerLeftWert = neuerLeftWertAlsZahl + "px";
- // neuen Wert im DOM setzen
- if (neuerLeftWertAlsZahl > 0 && neuerLeftWertAlsZahl < 500) {
- $("#mario").css("left", neuerLeftWert);
- }
- });
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement