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; } } }
我的第一排的图片有点特殊· 有3张一样高的· 0 1 2 3 4 5 0,2,3,都是135px高度,现在我所有的下面图,全部积压在第一张图下面了!不知所措!
第24最后好像没加 'px'