JS随机生成方块

JS随机生成方块-许俊活

网页主体代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>JS随机方块</title>
		<link rel="stylesheet" href="css/style.css"/>

	</head>
	<body>
		<div id="container">
			
		</div>
		<script src="js/tool.js"></script>
		<script src="js/box.js"></script>
		<script src="js/main.js"></script>
		<script>
			
		</script>
	</body>
</html>

tool.js的代码

var Tools={
	getRandom:function(min,max){
		return Math.floor(Math.random() * (max - min)) + min;
	}
}

box.js的代码

function Box(parent,options){
	options=options||{};
	//设置对象的属性
	this.backgroundColor=options.backgroundColor||'red';
	this.width=options.width||20;
	this.height=options.height||20;
	this.x=options.x || 0;
	this.y=options.y || 0;
	//创建对应的div
	this.div=document.createElement('div');
	parent.appendChild(this.div);
	this.parent=parent;
	//设置div的样式
	this.init();
}
//初始化div(方块)的样式
Box.prototype.init=function(){
	var div=this.div;
	div.style.backgroundColor=this.backgroundColor;
	div.style.width=this.width+'px';
	div.style.height=this.height+'px';
	div.style.left=this.x+'px';
	div.style.top=this.y+'px';
	//脱离文档流
	div.style.position='absolute'
}
Box.prototype.random=function(){
	var x=Tools.getRandom(0,this.parent.offsetWidth/this.width-1)*this.width;
	var y=Tools.getRandom(0,this.parent.offsetHeight/this.height-1)*this.height;
	this.div.style.left=x + 'px';
	this.div.style.top=y + 'px';
}

main.js的代码

//生成10个方块 随机生成颜色
//获取容器
var container=document.getElementById("container");
var array=[];
for(var i=0;i<10;i++){
	var r=Tools.getRandom(0,255);
	var g=Tools.getRandom(0,255);
	var b=Tools.getRandom(0,255);
	var box=new Box(container,{
		backgroundColor:'rgb('+ r +','+ g +','+ b +')'
	});
	array.push(box);
}
setInterval(randomBox,500)
//页面加载,先设置随机位置
randomBox();
function randomBox(){
	//随机生成方块的坐标
	for(var i=0;i<array.length;i++){
		var box=array[i];
		box.random();
	}
}

猜你喜欢

转载自blog.csdn.net/fdsgfd43432/article/details/106908741