随机方块

1:tools.js

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

2:

// 生成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();
}
}

3:

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';
}

原文地址:https://www.cnblogs.com/pxxdbk/p/12502743.html