运动的小球自动变键盘控制
<!DOCTYPE html>,
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box{ width: 400px;height: 400px;border: 1px solid black;position: relative;}
.ball{width: 30px;height: 30px;border-radius: 50%;background-color: red;position: absolute;left: 0;top: 0;}
</style>
</head>
<body>
<div class="box">
<div class="ball">
</div>
</div>
</body>
<script type="text/javascript">
var obox = document.querySelector(".box");
var oball = document.querySelector(".ball");
var a;
var b;
var c;
var d;
document.onclick = function(){
清楚计时器,防止多次点击出现多个计时器,小球运动速度依次增加
clearInterval(a);
clearInterval(b);
clearInterval(c);
clearInterval(d);
建立几个计时器,每当运动到大边框时清楚计时器,建立另一个计时器,换一个方向运行
a=setInterval(function(){
if(oball.offsetLeft>370){
oball.offsetLeft=370;
clearInterval(a);
b=setInterval(function(){
if(oball.offsetTop>370 ){
oball.offsetTop=370;
clearInterval(b);
c=setInterval(function(){
if(oball.offsetLeft<0){
oball.offsetLeft=0;
clearInterval(c);
d=setInterval(function(){
if(oball.offsetTop<0 ){
oball.offsetTop=0
}else{
oball.style.top = oball.offsetTop-5+"px"
}
},30)
}else{
oball.style.left = oball.offsetLeft-5+"px"
}
},30)
}else{
oball.style.top = oball.offsetTop+5+"px"
}
},30)
}else{
oball.style.left=oball.offsetLeft+5+"px"
}
},30)
}
键盘按下时清空所有计时器,由键盘来控制
document.onkeydown=function(eve){
clearInterval(a);
clearInterval(b);
clearInterval(c);
clearInterval(d);
e=eve||window.event;
if(e.keyCode==37){
if(oball.offsetLeft<0){
oball.offsetLeft=0
}else{
oball.style.left=oball.offsetLeft-5+"px";
}
}
if(e.keyCode==38){
if(oball.offsetTop<0){
oball.offsetTop=0
}else{
oball.style.top=oball.offsetTop-5+"px";
}
}
if(e.keyCode==39){
if(oball.offsetLeft>370){
oball.offsetLeft=370
}else{
oball.style.left=oball.offsetLeft+5+"px";
}
}
if(e.keyCode==40){
if(oball.offsetTop>370){
oball.offsetTop=370
}else{
oball.style.top=oball.offsetTop+5+"px";
}
}
}
</script>
</html>