首页 新闻 搜索 专区 学院

这是一段简单的贪吃蛇代码,可移动的时候为什么会晃动

0
悬赏园豆:20 [已关闭问题] 关闭于 2016-11-16 17:21

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
width: 100%;
height: 100%;
position: relative;
}
#head{
width: 30px;
height: 30px;
border: 1px black solid;
position: absolute;
line-height: 30px;
text-align: center;
position: absolute;

}
.body{
width: 30px;
height: 30px;
border: 1px black solid;
position: absolute;
left: 30px;
line-height: 30px;
text-align: center;
}
#tail{
width: 30px;
height: 30px;
border: 1px solid;
position: absolute;
line-height: 30px;
text-align: center;
left: 60px;
}
</style>
</head>
<body>
<div id="snake">
<div id="head">头</div>
<div class="body">身</div>
<div id="tail">尾</div>
</div>
<script>
var body = document.getElementsByClassName('body');

var speedX = 0;
var speedY = 30;

function snakeMove(){
var x = head.offsetLeft + speedX;
var y = head.offsetTop + speedY;
for(var i = snake.children.length-1;i>0;i--){
snake.children[i].style.left = snake.children[i-1].offsetLeft + "px";
snake.children[i].style.top = snake.children[i-1].offsetTop + "px";
}
head.style.left = x + "px";
head.style.top = y + "px";
}

var timer = setInterval(snakeMove,800);

document.addEventListener("keydown",function(event){
var event = event || window.event;//兼容
var keyCode = event.keyCode || event.which;//兼容
switch(event.keyCode){
case 37:
if(speedX == 0){
speedX = -30;
speedY = 0;
}
if(speedX == 30){
return false;
}
break;
case 38:
if(speedY == 0){
speedX = 0;
speedY = -30;
}
if(speedY == 30){
return false;
}
break;
case 39:
if(speedX == 00){
speedX = 30;
speedY = 0;
}
if(speedX == -30){
return false;
}
break;
case 40:
if(speedY == 00){
speedX = 0;
speedY = 30;
}
if(speedY == -30){
return false;
}
break;
default:
return;
break;
}
snakeMove();
},false);
</script>
</body>
</html>

 

按方向的时候,整个屏幕会晃动一下,找不出原因,请高手指教

sahk的主页 sahk | 初学一级 | 园豆:110
提问于:2016-11-16 14:22
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册