<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用键盘上下左右键控制小球移动</title>
<style>
*{
margin:0;
padding:0;
}
#ball{
200px;
height: 200px;
background: pink;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<div id="ball"></div>
</body>
<script>
//获取元素
var ball = document.getElementById('ball');
//定义小球每次移动的步径
var step = 1;
//定义小球水平、垂直方向移动定时器标志
var runX,runY;
//为使小球运行更流畅,加入水平移动定时器
function moveX(step){
console.log(runX);
if(runX){
return;
}
runX = setInterval(function(){
var newLeft = ball.offsetLeft + step;
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
if(newLeft <= 0){
newLeft = 0;
}
if(newLeft >= clientWidth - ball.offsetWidth){
newLeft = clientWidth - ball.offsetWidth;
}
ball.style.left = newLeft + 'px';
},5);
}
//为使小球运行更流畅,加入垂直移动定时器
function moveY(step){
if(runY){
return;
}
runY = setInterval(function(){
var newTop = ball.offsetTop + step;
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
if(newTop <= 0){
newTop = 0;
}
if(newTop >= clientHeight - ball.offsetHeight){
newTop = clientHeight - ball.offsetHeight;
}
ball.style.top = newTop + 'px';
},5);
}
//键盘按键按下时小球移动
window.onkeydown = function(e){
//兼容性写法
var e = e || window.event;
//使用switch结构判断键盘按下的是哪个键
switch(e.keyCode){
case 37:
moveX(-step);
break;
case 38:
moveY(-step);
break;
case 39:
moveX(step);
break;
case 40:
moveY(step);
break;
}
}
//键盘按键抬起时,小球停止移动
window.onkeyup = function(){
//清除定时器
clearInterval(runX);
runX = undefined;
clearInterval(runY);
runY = undefined;
}
</script>
</html>