JSFiddle - React, Tailwind, and code Playground
HTML
<div class="starship" id="starship"></div>
CSS
#starship{
width:100px;
height:100px;
background-color:blue;
}
JavaScript
function moveRect(e){
var blueRect = document.getElementById("starship");
// получаем стиль для starship
var cs = window.getComputedStyle(blueRect);
var left = parseInt(cs.marginLeft);
var top = parseInt(cs.marginTop);
switch(e.keyCode){
case 37: // если нажата клавиша влево
if(left>0)
blueRect.style.marginLeft = left - 10 + "px";
break;
case 38: // если нажата клавиша вверх
if(top>0)
blueRect.style.marginTop = top - 10 + "px";
break;
case 39: // если нажата клавиша вправо
if(left < document.documentElement.clientWidth - 100)
blueRect.style.marginLeft = left + 10 + "px";
break;
case 40: // если нажата клавиша вниз
if(top < document.documentElement.clientHeight - 100)
blueRect.style.marginTop = top + 10 + "px";
break;
}
}
addEventListener("keydown", moveRect);