js div 隨着鍵盤上下左右箭頭移動


.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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM