/** * Created by Administrator on 2017/7/12. */ window.onload=function(){ waterfall('main','box'); }; function waterfall(parent,box) { //取出main下的所有class为box的元素 var oParent = document.getElementById(parent); var oBoxs = getByClass(oParent, box); //console.log(oBoxs); //计算列数 var oBoxW = oBoxs[0].offsetWidth; var cols = Math.floor(document.documentElement.clientWidth / oBoxW); //设置main的宽度 oParent.style.cssText='width:'+oBoxW*cols+'px;margin:0 auto'; // oParent.style.width = oBoxW * cols + "px"; //oParent.style.margin = "0 auto"; var hArr = []; for (var i = 0; i < oBoxs.length; i++) { if (i < cols) { hArr.push(oBoxs[i].offsetHeight); }else{ var minH=Math.min.apply(null,hArr); var index=getMinIndex(hArr,minH); oBoxs[i].style.position="absolute"; oBoxs[i].style.top=minH+"px"; oBoxs[i].style.left=oBoxs[index].offsetLeft+"px"; hArr[index]+=oBoxs[i].offsetHeight; } } } //找到所有class是box的元素 function getByClass(parent,clsName){ var boxArr=[];//获取取得的box元素数组 var oElements=parent.getElementsByTagName("*");//取父元素下的所有内容 //对获取的元素进行遍历,找到传入的clsName for(var i=0;i<oElements.length;i++) { if (oElements[i].className == clsName) { boxArr[i].push(oElements[i]); } } return boxArr; } //获取当前最低高度的索引值 function getMinIndex(arr,val){ // for(var i in arr){ // if(arr[i]==val){ // return i; // } // } for(var i=0;i<arr.length;i++){ if(arr[i]==val){ return i; } } }
Uncaught TypeError: Cannot read property 'push' of undefined
at getByClass (waterFallJSEX.js:46)
at waterfall (waterFallJSEX.js:12)
at window.onload (waterFallJSEX.js:6)
FSYu
相关分类