<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
width: 100%;
}
.main{
width: 100%;
height: 100%;
border: 5px solid pink;
box-sizing: border-box;
position: relative;
}
.fk{
height: 50px;
width: 50px;
background: red;
position: absolute;
}
.sj{
height: 50px;
width: 50px;
background: blue;
position: absolute;
}
</style>
</head>
<body>
<div class="main">
<div class="fk">
</div>
</div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var yg = {
main:$('.main'),
fk:$('.fk'),
timer:null,
num:1,
yd:function(){
l = this.fk.position().left;//小方块的left
t = this.fk.position().top;//小方块的top
yg.sj();
$(document).keyup(function(e){
switch (e.keyCode){
case 37://键盘左键,就要div往左走
//往左走就是让div的left减少
yg.num = -1;
clearInterval(yg.timer)
yg.timer=setInterval(yg.xz,1)//yg.xz表示小方块的X轴移动函数
break;
case 38:
yg.num = -1;
clearInterval(yg.timer)
yg.timer=setInterval(yg.yz,1)//yg.yz表示小方块的Y轴移动函数
break;
case 39:
yg.num = 1;
clearInterval(yg.timer)
yg.timer=setInterval(yg.xz,1)
break;
case 40:
yg.num = 1;
clearInterval(yg.timer)
yg.timer=setInterval(yg.yz,1)
break;
}
});
},
xz:function(){
//如果num为-1,则减少,为1则增加
l += yg.num;
if(l<=0||l>=yg.main.width()-yg.fk.width()){
clearInterval(yg.timer);
}
yg.pz();
yg.fk.css('left',l);
},
yz:function(){
//如果num为-1,则减少,为1则增加
t += yg.num;
if(t<=0||t>=yg.main.height()-yg.fk.height()){
clearInterval(yg.timer);
}
yg.pz();
yg.fk.css('top',t);
},
sj:function(){
do{
x = Math.floor(Math.random()*(yg.main.width()-50));
y = Math.floor(Math.random()*(yg.main.height()-50));
}while (Math.abs(l-x)<50||Math.abs(t-y)<50);//一旦x或者y出现碰撞的情况,就循环,重新生成X,Y
div = $('<div></div>');
div.addClass('sj');
yg.main.append(div);
div.css({
left:x,
top:y
})
},
pz:function(){
if(Math.abs(l-x)<50&&Math.abs(t-y)<50){
div.remove();
yg.sj();
}
}
}
yg.yd();
</script>
</html>