先來看看最後實現的效果吧
實現方法呢也是非常簡單,
首先創建了一個產生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);
}