题目:创建10个位置随机、颜色随机的盒子,每隔一段时间,需要更换这10个盒子的位置
一、盒子的原始html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>产生10个小盒子,颜色随机位置随机</title> <style> .box{ width: 800px; height: 600px; background-color: skyblue; position: relative; } </style> </head> <body> <div class="box"></div> </body> </html>
二、创建产生的小盒子对象
function Box(parent,options) {
options = options || {};
this.width = options.width || 25;
this.height = options.height || 25;
this.backgroundColor = options.backgroundColor || "red" ;
this.x = options.x || 0;
this.y = options.y || 0;
this.dom = document.createElement("div");
this.parent = parent;
this.init();//这里是调用初始化方法
}
三、创建小盒子的初始化方法
Box.prototype.init = function () {
var oDiv = this.dom;
oDiv.style.width = this.width + "px";
oDiv.style.height = this.height + "px";
oDiv.style.backgroundColor = this.backgroundColor;
oDiv.style.position = "absolute";
oDiv.style.left = this.x + "px";
oDiv.style.top = this.y + "px";
this.parent.appendChild(oDiv);
}
四、引入通用的方法工具库
//产生min-max的随机数,包括min和max function toRandom(min, max) { return Math.round(Math.random() * (max - min)) + min; // return Math.floor(Math.random()*(max-min+1))+min; // return Math.ceil(Math.random()*(max-min+1))+min-1; } //获取随机颜色 function getColor() { var res = "#"; var arr = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']; for (let i = 0; i < 6; i++) { res += arr[toRandom(0, 16)]; } return res; }
五、写具体代码实现小盒子的随机
var parent = document.querySelector(".box"); // new Box(parent); // for (let i = 0; i < 10; i++) { // new Box(parent,{x:toRandom(0,775), // y:toRandom(0,575), // backgroundColor:getColor()}); // } setInterval(function () { //删除之前生成的小盒子 for (var i = 0; i < parent.children.length; i++) { parent.removeChild(parent.children[i]); i--; } //生成新的盒子 for (var i = 0; i < 3; i++) { var box = new Box(parent,{x:toRandom(0,775), y:toRandom(0,575), backgroundColor:getColor()}); } },1000);
六、另外还可以将这个位置变换放到Box的原型上去
Box.prototype.random = function () { var oDiv = this.dom; setInterval(function () { oDiv.style.top = toRandom(0, 575) + "px"; oDiv.style.left = toRandom(0, 775) + "px"; oDiv.style.backgroundColor = getColor(); },1000); }
for (let i = 0; i < 3; i++) { new Box(parent,{x:toRandom(0,775), y:toRandom(0,575), backgroundColor:getColor()}); }
七、为了防止变量污染,我们会将变量放到一个对象中,进行统一管理
var Tool = { //产生min-max的随机数,包括min和max toRandom:function (min, max) { return Math.round(Math.random() * (max - min)) + min; }, //获取随机颜色 getColor:function () { var res = "#"; var arr = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']; for (let i = 0; i < 6; i++) { res += arr[toRandom(0, 16)]; } return res; } }
当使用时,只需要增加Tool. 即可