console.log(clos)输出列数为7,浏览器显示为6列,且前第七个和第八个图片(第二列的一和二)没有内边距
// JavaScript Document
window.onload=function(){
waterfall("main","box");
}
function waterfall(parent,box){
var oParent=document.getElementById(parent);
getByClass(oParent,box);
var oBoxs=getByClass(oParent,box);
var aBoxW=oBoxs[0].offsetWidth;
var cols=Math.floor(document.documentElement.clientWidth/aBoxW);
oParent.style.cssText='width:'+aBoxW*cols+'px;margin:auto';
var hArr=[];
for(var i=0;i<oBoxs.length;i++){
if(i<cols-1){
hArr.push(oBoxs[i].offsetHeight);
}else{
var minH=Math.min.apply(null,hArr);
var index=getMinHIndex(hArr,minH);
oBoxs[i].style.position="absolute";
oBoxs[i].style.top=minH+'px';
//oBoxs[i].style.left=aBoxW*index+'px';
oBoxs[i].style.left=oBoxs[index].offsetLeft+'px';
hArr[index]+=oBoxs[i].offsetHeight;
}
}
console.log(cols);
console.log(hArr);
}
function getByClass(parent,clsName){
var boxArr=[];
oElements=parent.getElementsByTagName("*");
for(var i=0;i<oElements.length;i++){
if(oElements[i].className==clsName){
boxArr.push(oElements[i]);
}
}
return boxArr;
}
function getMinHIndex(arr,val){
for(var i in arr){
if(arr[i]==val){
return i;
}
}
}