<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机方块</title>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="box">
</div>
</body>
</html>
<script src="tools.js"></script>
<script src="box.js"></script>
<script src="main.js"></script>
<script>
</script>
*{
margin: 0px;
padding: 0px;
}
#box{
position: relative;
width: 700px;
height: 500px;
background-color: slategrey;
}
var tools={
getRandom:function(min,max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
function Box(parent,option) {
option=option||{};
this.backgroundColor=option.backgroundColor||"red";
this.width=option.width||20;
this.height=option.height||20;
this.x=option.x||0;
this.y=option.y||0;
this.div=document.createElement("div");
parent.appendChild(this.div);
this.parent=parent;
this.init();
}
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";
}
var box=document.getElementById("box");
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 bo=new Box(box,{
backgroundColor:'rgb('+r+','+g+','+b+')'
})
array.push(bo);
}
setInterval(randoms,500);
randoms();
function randoms() {
for (var i = 0; i < array.length; i++) {
var box=array[i];
box.random();
}
}
|