先上圖看效果吧
文件架構如下:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>隨機生成方塊</title>
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div class="map"></div>
<!-- 先引用tool.js -->
<script src="./js/tool.js"></script>
<script src="./js/box.js"></script>
<script src="./js/main.js"></script>
<script>
// var map = document.querySelector('.map');
// for (let i = 0; i < 10; i++) {
// var box = new Box({
// width: 30
// });
// box.render(map);
// box.random();
// }
</script>
</body>
</html>
box.js 類的封裝:
// // 構造函數Box
// 屬性
// bgc
// width和height
// x和y
// 私有
var _position = 'absolute';
var _map = null;
// var _div = null;
function Box(options) {
options = options || {}; //如果傳過的內容爲空,則返回空對象;不爲空爲傳入值。
this.backgroundColor = options.backgroundColor || 'pink';
this.width = options.width || 20;
this.height = options.height || 20;
this.x = options.x || 0;
this.y = options.y || 0;
this._div = null;
}
Box.prototype.rander = function(map) {
// rander把盒子對象渲染到畫布上
// 動態創建div
_map = map;
var div = document.createElement('div');
this._div = div;
map.appendChild(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 = _position;
}
Box.prototype.random = function() {
if (!_map) return;
this.x = Tool.getRandom(0, map.offsetWidth / this.width - 1) * this.width;
this.y = Tool.getRandom(0, map.offsetHeight / this.height - 1) * this.height;
this._div.style.left = this.x + 'px';
this._div.style.top = this.y + 'px';
}
// var box = new Box();
tool.js 工具對象:
var Tool = { //工具對象
getRandom: function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
main.js 入口函數
// 入口函數,一般只有一個
var map = document.querySelector('.map');
var arr = [];
for (var i = 0; i < 10; i++) {
var r = Tool.getRandom(0, 255);
var g = Tool.getRandom(0, 255);
var b = Tool.getRandom(0, 255);
var box = new Box({
backgroundColor: 'rgba(' + r + ',' + g + ',' + b + ')',
});
box.rander(map);
arr.push(box);
}
// 定時隨機生成盒子位置
setInterval(random, 500);
function random() {
arr.forEach(function(item) {
item.random();
});
}
index.css
* {
margin: 0;
padding: 0;
}
.map {
width: 700px;
height: 600px;
background-color: #343334;
}
需要源碼(文件)可以私