demo:http://leozdgao.github.io/demo/responsive_waterfall/
演示图:
核心代码:
responsive_waterfall.js
(function() { var waterfall = function(opts) { var minboxwidth; object.defineproperty(this, 'minboxwidth', { get: function() { return minboxwidth; }, set: function(value) { if(value 1000) value = 1000; minboxwidth = value; } }); opts = opts || {}; var containerselector = opts.containerselector || '.wf-container'; var boxselector = opts.boxselector || '.wf-box'; // init properties this.minboxwidth = opts.minboxwidth || 250; this.columns = []; this.container = document.queryselector(containerselector); this.boxes = this.container ? array.prototype.slice.call(this.container.queryselectorall(boxselector)) : []; // compose once in constructor this.compose(); // handle the image or something which might change size after loaded var images = this.container.queryselectorall('img'), that = this; var clr; for (var i = 0; i 0) { // create column div this.columns = []; var width = (100 / num) + '%'; while(num--) { var column = document.createelement('div'); column.classname = 'wf-column'; column.style.width = width; this.columns.push(column); this.container.appendchild(column); } } } // get the index of shortest column waterfall.prototype.getminheightindex = function() { if(this.columns && this.columns.length > 0) { var min = this.columns[0].clientheight, index = 0; for (var i = 1; i < this.columns.length; i++) { var columnelem = this.columns[i]; if(columnelem.clientheight < min) { min = columnelem.clientheight; index = i; } } return index; } else return -1; } // compose core waterfall.prototype.compose = function(force) { var num = this.computenumberofcolumns(); var cols = this.columns.length; if(force || num != cols) { // remove old column for (var i = 0; i < this.columns.length; i++) { var columnelem = this.columns[i]; columnelem.remove(); } // init new column this.initcolumns(num); // compose for (var i = 0, l = this.boxes.length; i < l; i++) { var box = this.boxes[i]; this.addbox(box); } } } // add a new box to grid waterfall.prototype.addbox = function(elem) { // push if new box if(this.boxes.indexof(elem) -1) { var column = this.columns[columnindex]; column.appendchild(elem); } } window.waterfall = waterfall;})()
以上所述就是本文给大家分享的全部内容了,希望能够对大家熟练使用javascript有所帮助。
