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
标签:10,style,oDiv,px,js,div,oEvent,上下左右,keyCode 来源: https://www.cnblogs.com/benbenbai/p/11413557.html