// var a = document.getElementById("box");
// var main = document.getElementById("main");
// 键盘按下
// document.addEventListener("keydown",keydown);
// function keydown(e){
// //表示键盘监听所触发的事件,同时传递参数e
// switch(e.keyCode){
// case 37: //left
// console.log("左键" + e.keyCode);
// console.log(box.style.left);
// box.style.left = parseInt(box.style.left) - 10 + 'px';
// break;
// case 39: //right
// console.log("右键" + e.keyCode);
// box.style.left = parseInt(box.style.left) + 10 + 'px';
// break;
// }
// }
function move() {
var a = document.getElementById("box");
a.style.left = 0;
a.style.top = 0;
document.onkeydown = function(e) {
var e = window.event ? window.event : e;
if(e.keyCode == 38) { //up
a.style.top = parseInt(a.style.top) - 50 + 'px';
//注意要用parseInt 因为a.style.top类型是字符串
}
if(e.keyCode == 40) { //down
a.style.top = parseInt(a.style.top) + 50 + 'px';
}
if(e.keyCode == 37) { //left
a.style.left = parseInt(a.style.left) - 50 + 'px';
}
if(e.keyCode == 39) { //right
a.style.left = parseInt(a.style.left) + 50 + 'px';
}
}
}
<div class="main" id="main">
<div class="box" id="box"></div>
</div>
.main{
width: 500px;
height: 600px;
border: 2px solid #666;
position: relative;
}
.main .box{
width: 50px;
height: 50px;
background: skyblue;
position: absolute;
bottom: 300px;
left: 200px;
}