先来看看最后实现的效果吧
实现方法呢也是非常简单,
首先创建了一个产生div块的函数,然后创建一个产生随机颜色的函数,最后通过for循环制造50个随机大小、位置、颜色的div块
代码附上:
function createDiv(_width, _height, _color) {
var str = "";
str += " <div style=' ";
str += "width:" + _width + "px;";
str += "height:" + _height + "px;";
str += "background-color:" + _color + ";";
str += "position:absolute;";
str += "left:" + Math.random() * 1000 + "px;";
str += "top:" + Math.random() * 600 + "px;";
str += "'></div>"
document.write(str);
}
function randomColor() {
var color = "#";
for (var i = 0; i < 6; i++) {
color += parseInt(Math.random() * 16).toString(16);
}
return color;
}
var w, c;
for (var i = 0; i < 50; i++) {
w = Math.random() * 50 + 50;
c = randomColor();
createDiv(w, w, c);
}