淘先锋技术网

首页 1 2 3 4 5 6 7

.box{
width: 10px;
height: 10px;
background-color: #ccc;
position:absolute;
}
</style>
<body>

<div class='box' id="div1"></div>
<script>
document.onkeydown = function(ev){
var oEvent = ev||event;
var oDiv = document.getElementById('div1');

if(oEvent.keyCode == 39){
oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
}
else if(oEvent.keyCode == 37){
oDiv.style.left = oDiv.offsetLeft - 10 + 'px';
}
else if(oEvent.keyCode == 38){
oDiv.style.top = oDiv.offsetTop - 10 + 'px';
}
else if(oEvent.keyCode == 40){
oDiv.style.top = oDiv.offsetTop + 10 + 'px';
}
};
</script>

 

重点:offsetTop    offsetLeft

转载于:https://www.cnblogs.com/benbenbai/p/11413557.html