//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)
随机方块 、 构造 渲染 随机 实现功能,this 和在那里调用函数很重要
最新推荐文章于 2022-09-15 15:01:10 发布