大致样式如下
- 将父盒子设定宽高,相对定位,子盒子定宽,绝对定位
- 根据父盒子和多个等宽不等高的子盒子的宽度计算一共有多少列
- 将每一列目前的高度存到数组中,插入下一个元素时比较当前数组哪一列更空,计算top和left值,插入后更新高度数组
function waterfall() {
var pos = [],
$items = $('.waterfall-item'),
fontSize = getComputedStyle(window.document.documentElement)['font-size'].split('px')[0],
_box_width = $('.liked-content-wrap').width()/fontSize,
_owidth = $items.eq(0).width()/fontSize + .2,
_num = Math.floor(_box_width/_owidth);
//确定一行有多少列
var i = 0;
for (; i < _num; i++) {
pos.push([i*_owidth,0]);
}
//给每个元素设定top和left 放到当前比较少的那一列
$items.each(function() {
var _this = $(this),
_temp = 0,
_height = _this.height()/fontSize + .23;
for (var j = 0; j < _num; j++) {
if(pos[j][1] < pos[_temp][1]){
//暂存top值最小那列的index
_temp = j;
}
}
this.style.cssText = 'left:'+(pos[_temp][0] + .20)+'rem; top:'+pos[_temp][1]+'rem;';
//插入后,更新下该列的top值
pos[_temp][1] = pos[_temp][1] + _height;
});
}
复制代码
注:
- 由于是在手机端用到的,计算的时候会将px转为rem