随机产生小方块
为贪吃蛇准备
*总结
* window.Random=new Random(); 实例化对象暴露给window
* +"px"
* 取到map选择器
* 1.offsetWidth属性可以返回对象的padding+border+width属性值之和,
* style.width返回值就是定义的width属性值。
2.offsetWidth属性仅是可读属性,而style.width是可读写的。
3.offsetWidth属性返回值是整数,而style.width的返回值是字符串,并且带有单位。
4.style.width仅能返回以style方式定义的内部样式表的width属性值。
* appendChild()可向节点的子节点列表的末尾添加新的子节点
var node=document.getElementById("myList2").lastChild;
document.getElementById("myList1").appendChild(node);
* absolute : 将对象从文档流中拖出,使用left,right,top,bottom等属性进行绝对定位。
而其层叠通过css z-index属性定义。此时对象不具有边距,但仍有补白和边框
relative : 对象不可层叠,但将依据left,right,top,bottom等属性在正常文档流中偏移位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
</script>
<style>
.map {
width: 600px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
</head>
<body>
<div class="map"></div>
<script>
(function (win) {
function Random() {
}
Random.prototype.getRandom=function (min,max) {
return Math.floor(Math.random()*(max-min)+min);
};
win.Random=new Random();
})(window);
(function (window) {
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);
this.render(map);
};
Food.prototype.render=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,"green");
fd.init(map);
})(window);
</script>
</body>
</html>