87,907
社区成员
发帖
与我相关
我的任务
分享
window.onload = function(){
//waterfall('main','box')
waterfall('main','box')
}
function waterfall(parent,box){
var oParent = document.getElementById(parent);
var boxs = getClassName(oParent,box);
var oBoxW = boxs[0].offsetWidth;
var cols = Math.floor((document.documentElement.clientWidth)/oBoxW);
//大盒子宽度
oParent.style.cssText = 'width:'+ oBoxW*cols + 'px;margin:0 auto';
var hArr = [];
for (var i = 0; i < boxs.length; i++) {
if (i < cols) {
hArr.push(boxs[i].offsetHeight)
}else {
var minH = Math.min.apply(null,hArr);
var index = getMinIndex(hArr,minH);
boxs[i].style.position = 'absolute';
boxs[i].style.top = minH + 'px';
boxs[i].style.left = boxs[index].offsetLeft;
//hArr[index] +=boxs[i].offsetHeight;
hArr[index] += boxs[i].offsetHeight;
}
}
}
function getClassName(parent,clsname){
var oElements = parent.getElementsByTagName('*')
var boxs = []
for (var i = 0; i < oElements.length; i++) {
if (oElements[i].className == clsname) {
boxs.push(oElements[i])
}
}
return boxs
}
function getMinIndex(arr,value){
for (var i in arr) {
if (arr[i] == value) {
return i;
}
}
}
<div class='main' id='main'>
<div class="box">
<div class="pic">
<img src="img/0.jpg" alt="" />
</div>
</div>
</div>