console
function Masonry(domObj, columnCount) {
if (!domObj || !domObj instanceof HTMLElement) {
throw new Error('a valid HTMLElement required to be container');
}
domObj.classList.add('.masonry');
this.container = domObj;
this.columnCount = columnCount;
this.picStacks = [];
var masonry = this;
for (let i = 0; i < columnCount; i++) {
masonry.picStacks.push(new PicStack());
}
this.picStacks.forEach(function (stack) {
masonry.container.appendChild(stack.container);
});
}
Masonry.prototype.appendPic = function (pic) {
this.picStacks.reduce(function (a, b) {
if (b.height < a.height) {
return b;
}
return a;
}).push(pic);
}
function PicStack() {
this.pics = [];
this.height = 0;
this.container = document.createElement('div');
this.container.classList.add('pic-stack');
}
PicStack.prototype.push = function (pic) {
this.container.appendChild(pic);
this.pics.push(pic);
this.height += pic.offsetHeight;
}
PicStack.prototype.length = function () {
return this.pics.length;
}
let images = [];
for (let i = 0; i < 14; i++) {
let img = document.createElement('img');
var suffix = (i == 0 || i == 1 || i == 2)?('.jpeg'):('.jpg');
img.src = 'http://salpadding-img.nos-eastchina1.126.net/image/jpg/timg' + i + suffix;
images.push(img);
};
var marsonry = new Masonry(document.getElementById('masonry'), 3);
images.forEach(function(img){
marsonry.appendPic(img);
});
<div id="masonry" style="width:800px;" class="masonry">
*{
margin:0;
padding:0;
}
.masonry{
display: flex;
flex-direction: row;
}
.masonry img{
box-sizing: border-box;
padding: 5px;
width: 100%;
}
.pic-stack{
display: flex;
flex: 1;
flex-direction: column;
}