加粗样式
//对象:随机数 ,小方块
//产生随机数的对象
((function () {
//1.产生随机数的构造函数
function Random() {
}
//2.在原型中添加方法
Random.prototype.getRandom=function (max,min) {
return parseInt(Math.random()*(max-min)+min);//向下取整
}
//3.把局部对象暴露给window对象
window.Random=Random;
})());
var r=new Random();
//console.log(r.getRandom(10, 50));
//产生小方块
((function () {
//创建小方块的函数
function Food(width,height,color,x,y) {
this.width=width||20;
this.height=height||20;//20 默认小方块的宽高
this.color=color||"green";
//随机产生的x,y
this.x=x||0;
this.y=y||0;
//创建一个div盒子
this.ele=document.createElement("div");
}
//设置小方块显示的效果和位置-->显示在地图上
Food.prototype.init=function (map) {
//1.储存div元素对象
var div=this.ele;
//2.设置小方块的样式
div.style.width=this.width+"px";
div.style.height=this.height+"px";
div.style.backgroundColor=this.color;
div.style.position="absolute";
//3.把小方块添加到地图上
map.appendChild(div);
//设置随机的位置
this.render(map);
}
//产生随机的位置
Food.prototype.render=function (map) {
//随机数的区间 0-39 800-20=780 780/20=39
//随机的坐标
console.log(map)
this.x=r.getRandom(0,map.offsetWidth/this.width)*this.width;
this.y=r.getRandom(0,map.offsetHeight/this.height)*this.height;
this.ele.style.top=this.y+"px";
this.ele.style.left=this.x+"px";
}
var food=new Food();
food.init(document.getElementById("map"));
})());
做着随机产生小方块this.x=r.getRandom(0,map.offsetWidth/this.width)*this.width;这个地方不是很明白