1. 程式人生 > >隨機方塊 、 構造 渲染 隨機 實現功能,this 和在那裡呼叫函式很重要

隨機方塊 、 構造 渲染 隨機 實現功能,this 和在那裡呼叫函式很重要

//div id map
var Tools = {
getRandom: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) +  min;
    };
//  建構函式 渲染函式
function Box(parente, options) {  //建構函式是 options(作為一個物件)為各種屬性的集合  parent為渲染的地址
options = options || {};
this.width = options.width || 20;
this.height = options.height 
|| 20; //讓這個物件的高度 等於傳過來的引數的高度 下面可以設定 this.x = options.x || 0; this.y = options.y || 0; this.backgroundColorcolor = options.backgroundColor || 'red'; this.div = document.createElement('div'); //this指向的是呼叫建構函式的那個物件 parente.appendChild(this.div); //parent就是在哪裡建立的div div的父元素 this.parente = parente; //為下面 random
獲取盒子的寬度 //因為建構函式中的變數 是區域性變數,若下面的渲染要使用這個變數 可以吧這個變數通過this變成一個屬性 this.render(); } Box.prototype.render = function () { var div = this.div; // 為下面的 設定樣式 寫的方便 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.backgroundColor
= this.backgroundColorcolor; div.style.position = 'absolute'; } Box.prototype.random = function () { var x = Tools.getRandom(0, this.parente.offsetWidth / this.width - 1) * this.width; //this.parent 上面的parent為了讓這裡獲取到 而改變成this.parent var y = Tools.getRandom(0, this.parente.offsetHeight / this.height - 1) * this.height; this.div.style.left = x + 'px'; this.div.style.top = y + 'px'; } //實現功能 這裡是在其他地方測試程式碼的集合 var map = document.getElementById('map'); var arry = []; // 把下面建立好的div 放到一個數組裡 為了下面定時器做準備 在理解??? 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); //box就是 通過new Box 建立的一個物件 在for迴圈裡 建立了 十個box 引數的意思就是 在那裡建立 和隨機生成的顏色 //因為 在這裡生成十個box 所以 在這裡去渲染十個的顏色 backgroundColor作為options的一個屬性 其他的寬高位置等都是預設值 var box = new Box(map, { //用物件的方式傳參 // backgroundColor: 'rgb('+ r +','+ g +','+ b +')' backgroundColor: 'rgb('+ r +','+ g +','+ b +')' // backgroundColor: 'rgb('+ r +','+ g +','+ b +')' }); arry.push(box); } setInterval(function () { for (var i = 0; i < arry.length; i++) { var box = arry[i]; box.random(); //這裡呼叫 建構函式建立的物件裡的 random方法 隨機位置 } }, 600)