<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>follow me</title>
<style>
#border{
width:300px;
height:500px;
border:1px red solid;
margin:50px auto;
position:relative;
}
#kuai{
height:20px;
width:20px;
border-radius:10px;
border:1px red solid;
background:green;
position:absolute;
}
</style>
</head>
<body>
<div id="border">
<div id='kuai'>
</div>
</div>
</body>
<script>
var border=document.getElementById('border');
var div=document.getElementById('kuai');
//跟随鼠标移动
/*document.onmousemove=function (ev){
var Event=ev||event;
div.style.left=Event.clientX+'px';
div.style.top=Event.clientY+'px';
}*/
//方向键控制
var w,a,s,d;
var timer=null;
timer=setInterval(function (){
if(s){
div.style.top=div.offsetTop-10+'px';
if(div.offsetTop<=0){
//alert('');
div.style.top=0;
}
}
if(w){
div.style.top=div.offsetTop+10+'px';
}
if(a){
div.style.left=div.offsetLeft-10+'px';
if(div.offsetLeft<=0){
//alert('');
div.style.left=0;
}
}
if(d){
div.style.left=div.offsetLeft+10+'px';
}
},40)
document.onkeydown=function(ev){
var Event=ev||event;
switch(Event.keyCode){
case 37:
a=true;
break;
case 38:
s=true;
break;
case 39:
d=true;
break;
case 40:
w=true;
break;
}
}
document.onkeyup=function(ev){
var Event=ev||event;
switch(Event.keyCode){
case 37:
a=false;
break;
case 38:
s=false;
break;
case 39:
d=false;
break;
case 40:
w=false;
break;
}
}
</script>
</html>
添加回答
举报
0/150
提交
取消