前言:最近在看js中的事件,之前也一直有用到事件,用到最多的就是onclick单击事件,还有填写表单信息时的用到的onfocus聚焦时间,和onblur事件,最近看到了onmousemove鼠标移动事件,觉得很神奇,就突然很想写一个小游戏,用到了setInterval函数。游戏的功能也很简单,就是天上掉纸片,小人儿要不停的躲,一旦纸片和小人儿相撞,就会game over!代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
.move
{
margin-top: 0px;
width:40px;
height: 50px;
background: #ff0;
position:absolute;
z-index: 999;
}
.self
{
width:40px;
height: 50px;
background: #f0f;
position:absolute;
margin-top: 600px;
margin-left: 643px;
z-index: 999;
}
.self img
{
width:40px;
height: 50px;
border-radius: 20px;
}
</style>
<title>图图up up</title>
</head>
<body onload="moveDiv()">
<!--12个div就是空中的小纸片-->
<div class="move" style="margin-left:100px">
</div>
<div class="move" style="margin-left:200px">
</div>
<div class="move" style="margin-left:300px">
</div>
<div class="move" style="margin-left:400px">
</div>
<div class="move" style="margin-left:500px">
</div>
<div class="move" style="margin-left:600px">
</div>
<div class="move" style="margin-left:700px">
</div>
<div class="move" style="margin-left:800px">
</div>
<div class="move" style="margin-left:900px">
</div>
<div class="move" style="margin-left:1000px">
</div>
<div class="move" style="margin-left:1100px">
</div>
<div class="move" style="margin-left:1200px">
</div>
<!--小人儿用一张图片代替-->
<div id="self" class="self">
<img src="images/tutu.jpg">
</div>
</body>
<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("一不小心撞到了!!!游戏结束");
}
}
}
</script>
</html>
效果如图:
全部的代码就这些,动图做的效果不是很好,第一次做动图,发现有很多在线网站都可以,做起来很简单,还是免费的,开心!!!