<div id="self" class="self">
<img src="images/tutu.jpg">
<script type="text/javascript">
var alldiv = document.querySelectorAll('.move');
var selfdiv = document.getElementById("self");
var timer,flag;
function moveItem()
{
//用随机数决定哪一张纸片掉落
for (var j = 0; j < Math.round(Math.random()*11); j++)
{
var i = Math.round(Math.random()*11);
alldiv[i].style.top = alldiv[i].offsetTop + 20 +"px";
//掉落过程中改变纸片的颜色
var rgb='rgb('+Math.floor(Math.random()255)+','
+Math.floor(Math.random()255)+','
+Math.floor(Math.random()*255)+')';
alldiv[i].style.backgroundColor = rgb;
if (alldiv[i].offsetTop >= 600)
{
alldiv[i].style.top = "50px"; //当纸片落到底部,又重新回到起点
}
}
}
function moveDiv()
{
timer = setInterval(moveItem,20); //每隔20ms掉落
flag = setInterval(meeting,1); //间隔1ms判断是否相撞
}
var selfdiv = document.getElementById("self");
selfdiv.onmousedown = function(e) //鼠标点击小人儿开始移动
{
document.onmousemove = function(e) //小人儿跟着鼠标移动
{
if (e.clientY > 600)
{
selfdiv.style.marginTop = "600px"; //如果到达屏幕底部就不再往下
}
else if(e.clientX > 1300)
{
selfdiv.style.marginLeft = "1300px"; //到达最右部就回到不再往右
}
else
{
//小人儿的位置始终等于鼠标的位置
selfdiv.style.marginTop = e.clientY + "px";
selfdiv.style.marginLeft = e.clientX + "px";
}
}
}
function meeting()
{
for (var i = 0; i < alldiv.length; i++)
{
//判断是否相撞
if (Math.abs(alldiv[i].offsetTop-selfdiv.offsetTop) <= 50 &&
Math.abs(alldiv[i].offsetLeft-selfdiv.offsetLeft) <= 40)
{
clearInterval(flag);
clearInterval(timer);
alert("一不小心撞到了!!!游戏结束");
}
}
}