<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#map{
width: 800px;
height: 600px;
background-color: pink;
position: relative;
/*小方块要脱离标准文档流*/
}
</style>
</head>
<body>
<div id="map"></div>
<script>
//对象:随机数,小方块
//产生随机数的对象
((function () {
function Random() {
}
Random.prototype.getRandom=function (min,max) {
return parseInt(Math.random()*(max-min)+min)
}
window.Random=Random;
})())
var rm=new Random();
((function () {
function Food(width,height,color,x,y) {
this.width=width||20;
this.height=height||20;
this.color=color||"red";
this.x=x||0;
this.y=y||0;
this.element=document.createElement("div")
}
Food.prototype.init=function (map) {
var div=this.element;
div.style.width=this.width+"px";
div.style.height=this.height+"px";
div.style.background=this.color;
div.style.position="absolute";
map.appendChild(div);
this.cen(map);
}
Food.prototype.cen=function (map) {
this.x=rm.getRandom(0,map.offsetWidth/this.width)*this.width;
this.y=rm.getRandom(0,map.offsetHeight/this.height)*this.height;
this.element.style.left=this.x+"px";
this.element.style.top=this.y+"px";
console.log(this.element);
}
var food=new Food();
food.init(document.getElementById("map"))
})())
</script>
</body>
</html>
随机产生小方块
最新推荐文章于 2023-02-15 15:27:35 发布