<script type="text/javascript">
window.onload = function(){
waterfall("box");
}
function waterfall(cls){
//获取每个条目
var main = document.getElementById("main");
var boxs = main.getElementsByClassName(cls);
//计算页面现实的列数
var boxw = boxs[0].offsetWidth;
var clos = Math.floor(document.documentElement.clientWidth/boxw);
//设置main的宽度并居中
main.style.cssText = "width:"+clos*boxw+"px;margin:0 auto;";
// console.log(boxw);
// console.log(clos);
//将第一行元素高度存放于数组中
//获取最小高度,将第二航元素放置于此元素下
var hArr = [];
for(var i=0;i<boxs.length;i++){
var height = boxs[i].offsetHeight;
if(i<clos){
hArr.push(height);
}else{
var minH = Math.min.apply(null,hArr);
//遍历数组获取最小值索引,根据索引获取最小高度元素,将原来索引中的值更新为现有值加上第
var index = hArr.indexOf(minH);
var obj = boxs[index];
var left = obj.offsetLeft;
var height1 = obj.offsetHeight;
boxs[i].style.position="absolute";
boxs[i].style.top=minH+"px";
boxs[i].style.left=left+"px";
// boxs[i].style.cssText="position:absolute;top:"+minH+"px;left:"+left+"px;";
hArr[index]+=height1;
console.log(hArr[index]);
}
}
console.log(hArr);
}
</script>
var obj = boxs[index];
var left = obj.offsetLeft;
var height1 = obj.offsetHeight;
hArr[index]+=height1;
貌似height1应该是
boxs[i].offsetHeight才对,
boxs[index].offsetHeight求的始终是第一行的索引为index的值