<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<tbody>
<div style="background-color:black;height:500px;width:600px" >
<div id="mytanke" style="background-color:yellow;width:18px;height:20px;position:relative;"></div>
</div>
</tbody>
<script type="text/javascript">
var mytanke=document.getElementById("mytanke");
document.onkeydown=function(event){
var e = event || window.event || arguments.callee.caller.arguments[0];
var x=mytanke.offsetLeft;
var y=mytanke.offsetTop;
if(e && e.keyCode==37){ // zuo
mytanke.style.backgroundColor='red';
if(x>8){
mytanke.style.left=(x-1)+'px';
}
}
if(e && e.keyCode==38){ // shang
if(y>8){
var mm=parseInt(y)-1;
mytanke.style.top=mm+'px';
}
}
if(e && e.keyCode==39){ // you
if(x<600){
console.log(3333);
mytanke.style.left=(x+1)+'px';
}
}
if(e && e.keyCode==40){ // xia
console.log(4444);
if(y<500){
mytanke.style.top=(y+1)+'px';
}
}
};
</script>
</body>
</html>
不用用offsetTop/Left,自己打印出来看值就知道为什么了
var x = parseInt(mytanke.style.left)||0;
var y = parseInt(mytanke.style.top) || 0;
<!DOCTYPE html>