Advertisement
luistavares

JavaScript - Movimentando uma DIV

Oct 6th, 2017
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 0.84 KB | None | 0 0
  1. <html>
  2.     <head>
  3.         <title>Manipulando CSS</title>
  4.         <style>
  5.             #box{
  6.                 width: 50px;
  7.                 height: 50px;
  8.                 background-color: green;
  9.                 border-radius: 50px;
  10.             }
  11.         </style>
  12.         <script>
  13.             var x = 0;
  14.             var y = 0;
  15.             document.onkeydown = teclar;
  16.             function teclar(e){
  17.                 if (e.keyCode == 38) {     
  18.                     y = y - 20;
  19.                     document.getElementById('box').style.marginTop = y + 'px';
  20.                 }
  21.                 else if (e.keyCode == 40) {            
  22.                     y = y + 20;
  23.                     document.getElementById('box').style.marginTop = y + 'px';
  24.                 }
  25.                 else if (e.keyCode == 37) {            
  26.                     x = x - 20;
  27.                     document.getElementById('box').style.marginLeft = x + 'px';
  28.                 }
  29.                 else if (e.keyCode == 39) {            
  30.                     x = x + 20;
  31.                     document.getElementById('box').style.marginLeft = x + 'px';
  32.                 }
  33.             }
  34.         </script>
  35.     </head>
  36.     <body>
  37.         <div id='box'></div>   
  38.     </body>
  39. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement