HTML+CSS代码参考:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>案例--随机小方框</title>
<style>
.map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
</head>
<body>
<div class="map"></div>
</body>
</html>
JS代码参考:
// 利用自定义构造函数的方式
//产生随机数变量
(function(window){
function Random(){
}
Random.prototype.getRandom(max,min){
return Math.floor(Math.random()*(max-min)+min);
};
window.Random=new Random();
};)(window);
//产生小方块对象
(function(){
//选择器的方式获取元素对象
var map=document.querySelector("map");
//通过构造函数创建食物
function Food(width,height,color){
this.width=width||20;
this.height=height||20;
//横纵坐标
this.x=0;
this.y=0;
this.color=color;
this.element=document.createElement("div");//小方框元素
};
//初始化小方框的显示效果及位置------显示在地图上
Food.prototype.init=function(){
//设置小方块的样式
var div=this.element;
div.style.position="absolute";
div.style.width=this.width+"px";
div.style.height=this.height+"px";
div.style.backgroundColor=this.color;
map.appendchild(div);//在map中添加div
this.rander=(map);
};
//产生随机的位置
Food.prototype.rander=function(map){
//随机产生横纵坐标
var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width;
var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height;
this.x=x;
this.y=y;
var div=this.element;
div.style.left=this.x+"px";
div.style.top=this.y+"px";
};
var fd=new Food(20,20,"hotpink");
fd.init(map);
})(window);