<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none
}
.divClass{
position:absolute;
width:20px;
height:20px;
background-color:pink;
border-radius:50%;
}
#box{
position:relative;
}
</style>
</head>
<body style="height:1000px">
<div id="box">
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass"></div>
<div class="divClass">头</div>
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<input id="btnRight" type="button" value="右移" />
<input id="btnDown" type="button" value="下移" />
<input id="btnUp" type="button" value="上移" />
<input id="btnLeft" type="button" value="左移" />
</body>
</html>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript" src="js/moveJS1705.js"></script>
<script type="text/javascript">
//蛇的每一节的宽和高(20)
var unitWidth = 20;
var unitHeight = 20;
var direction = "右";
function initUI(){
let divObjs = $("#box").children;
for(let i=0;i<divObjs.length;i++){
divObjs[i].style.left = i*unitWidth+"px";
divObjs[i].style.top = "20px";
}
}
function startGo(){
setInterval(goStep,200);
}
//
function goStep(){
let divObjs = $("#box").children;
for(let i=0;i<divObjs.length-1;i++){
divObjs[i].style.left = divObjs[i+1].style.left;
divObjs[i].style.top = divObjs[i+1].style.top;
}
switch(direction){
case "左":{
//改变蛇头的位置
let left = parseInt(divObjs[divObjs.length-1].style.left);
divObjs[divObjs.length-1].style.left = left-unitWidth+"px";
} break;
case "上":{
//改变蛇头的位置
let top = parseInt(divObjs[divObjs.length-1].style.top);
divObjs[divObjs.length-1].style.top = top-unitHeight+"px";
} break;
case "右":{
//改变蛇头的位置
let left = parseInt(divObjs[divObjs.length-1].style.left);
divObjs[divObjs.length-1].style.left = left+unitWidth+"px";
} break;
case "下":{
//改变蛇头的位置
let top = parseInt(divObjs[divObjs.length-1].style.top);
divObjs[divObjs.length-1].style.top = top+unitHeight+"px";
} break;
default:;
}
}
window.onload = function(){
initUI();
startGo();
}
</script>