(function () { var waterfall = function (opt) { // 大盒子 this.el = document.getelementsbyclassname(opt.el)[0]; // 每一个方块 this.allitem = this.el.queryselectorall('div.wf-item'); // 几行 this.column = opt.column; // 间距 this.gap = opt.gap; // 计算每一个方块的宽度 this.w = (this.el.clientwidth - (this.column - 1) * this.gap) / this.column; this.headerarr = []; this.init(); } waterfall.prototype.init = function () { this.render(); } waterfall.prototype.render = function () { var minindex = null; // 给每一个方块添加宽度 for (var i = 0; i < this.allitem.length; i++) { this.allitem[i].style.width = this.w + 'px'; this.allitem[i].style.position = 'absolute'; if (i < this.column) { this.allitem[i].style.top = '0px'; this.allitem[i].style.left = i * (this.w + this.gap) + 'px'; this.headerarr.push(this.allitem[i].clientheight); } else { minindex = getminindex(this.headerarr); this.allitem[i].style.left = this.allitem[minindex].offsetleft + 'px'; this.allitem[i].style.top = this.headerarr[minindex] + this.gap + 'px'; this.headerarr[minindex] += this.allitem[i].clientheight + this.gap; } } this.el.style.height = getmax(this.headerarr) + 'px'; } // 查找数组中 最小值 并找出索引号 function getminindex(arr) { return arr.indexof(math.min.apply(null, arr)); } // 查找数组中 最大值 function getmax(arr) { return math.max.apply(null, arr); } window.waterfall = waterfall; })();