<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.map{
width:800px;
height:600px;
background-color:#ccc;
position:relative;
}
</style>
</head>
<body>
<div class="map"></div>
<script>
//产生随机数对象
(function(window){
function Random(){
}
Random.prototype.getRandom=function(min,max){
reutrn Math.floor(Math.random()*(max-min)+min);
};
//把局部对象暴露给window顶级对象,就成了全局对象
window.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(map){
//设置小方块的样式
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地图中
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,"red");
fd.init(map);
})(window);
</script>
</body>
</html>
javascript实现随机小方块小案例(原型)
最后发布:2020-11-30 09:48:07首次发布:2020-11-30 09:48:07