前言:最近在看js中的事件与纽,之前也一直有用到事件侣签,用到最多的就是onclick單擊事件,還有填寫表單信息時的用到的onfocus聚焦時間急迂,和onblur事件影所,最近看到了onmousemove鼠標移動事件,覺得很神奇僚碎,就突然很想寫一個小游戲猴娩,用到了setInterval函數(shù)。游戲的功能也很簡單勺阐,就是天上掉紙片卷中,小人兒要不停的躲,一旦紙片和小人兒相撞渊抽,就會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()
{
//用隨機數(shù)決定哪一張紙片掉落
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("一不小心撞到了@撩啤J酢!游戲結(jié)束");
}
}
}
</script>
</html>
效果如圖:
全部的代碼就這些愤估,動圖做的效果不是很好帮辟,第一次做動圖,發(fā)現(xiàn)有很多在線網(wǎng)站都可以玩焰,做起來很簡單由驹,還是免費的,開心N粼啊B闹炉!