Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.47 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="de">
  3. <head>
  4. <title>Mario</title>
  5. <style>
  6. div {
  7.   position: fixed;
  8. }
  9.  
  10. #meinSpielfeld {
  11.   left: 0;
  12.   top: 0;
  13.   width: 500px;
  14.   height: 500px;
  15.   background-color: black;
  16. }
  17.  
  18. #mario {
  19.   left: 10px;
  20.   top: 400px;
  21.   width: 80px;
  22.   height: 80px;
  23.   background-image: url(http://fluffynukeit.com/wp-content/uploads/2011/06/mario_running.gif);
  24. }
  25.  
  26. </style>
  27. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  28. </head>
  29. <body>
  30. <div id="meinSpielfeld">
  31.   <div id="mario"></div>
  32. </div>
  33. <script>
  34.     $(document).ready( function() {
  35.  
  36.       $("body").keydown(function(e) {
  37.   var aktuellerLeftWert = $("#mario").css("left"); // z.B. "50px"
  38.  
  39.   // Damit wir rechen können, müssen wir die Endung "px" loswerden
  40.   var aktuellerLeftWertAlsZahl = parseInt(aktuellerLeftWert);
  41.  
  42.   // Um wieviele Pixel verändern wir die Position?
  43.   var veraenderungDerPosition = 0;
  44.  
  45.   if (e.keyCode == 37) { // links
  46.     veraenderungDerPosition -= 5;
  47.   } else if (e.keyCode == 39) { // rechts
  48.     veraenderungDerPosition += 5;
  49.   }
  50.  
  51.   // Ein paar Pixel hinzufügen/abzählen und wieder "px" anhängen
  52.   var neuerLeftWertAlsZahl = aktuellerLeftWertAlsZahl + veraenderungDerPosition
  53.   var neuerLeftWert = neuerLeftWertAlsZahl + "px";
  54.  
  55.   // neuen Wert im DOM setzen    
  56.   if (neuerLeftWertAlsZahl > 0 && neuerLeftWertAlsZahl < 500) {
  57.    $("#mario").css("left", neuerLeftWert);
  58.   }
  59. });
  60.  
  61.  
  62.     });
  63. </script>
  64. </body>
  65. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement