10个小方块颜色 位置随机变化
在这里插入图片描述
style.css文件:
#container{
width: 800px;
height: 600px;
background-color:lightgrey;
position: relative;
}
tools.js文件:
var tools = {
getRandom: function(min,max){
return Math.floor(Math.random()*(max - min + 1)) + min;
}
}
box.js文件:
function Box(parent,options){
var 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 ;
this.position = 'absolute';
this.parent = parent;
this.div = document.createElement("div");
parent.appendChild(this.div);
this.init();
this.getRandomXY();
}
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.getRandomXY = function(){
var x = tools.getRandom(0, this.parent.offsetWidth/this.width - 1);
var y = tools.getRandom(0, this.parent.offsetHeight/this.height - 1);
this.div.style.left = x*this.width + 'px';
this.div.style.top = y*this.height + 'px';
}
index.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src = "js/tools.js"></script>
<script src = "js/box.js"></script>
<title>随机方块</title>
</head>
<body>
<div id="container"></div>
<script>
var parent = document.getElementById("container");
function flash(){
var array = parent.children;//将要删除的小box放入数组中
console.log(array);
if(parent.children.length > 0){
for(var i = 0; i < 10; i++){
parent.removeChild(array[0]);
}
}
if(parent.children.length == 0){
for(var i = 0; i < 10; i++){
var box = new Box(parent,{backgroundColor:'rgb(' + tools.getRandom(0,255) + ',' +tools.getRandom(0,255) + ',' + tools.getRandom(0,255) + ')'});
}
}
}
setInterval(flash,500);
</script>
</body>
</html>