九宫格算法
1、利用控件的索引index计算出控件所在的行号(索引 / 列数 = 5 / 3 = 1
)和列号(索引 % 列数 = 5 % 3 = 2
)
2、利用列号计算出控件的left距离(col*(boxW+mgXY)+“px”;)
3、利用行号计算出控件的top距离(row*(boxH+mgXY)+“px”;)
/**
* 实现瀑布流布局
*/
function waterFull(parent, child) {
//father auto
//get allBox and boxWidth
var father = document.getElementById('box');
var allBox = father.children;
var boxWidth = allBox[0].offsetWidth;
//get screenWidth
var screenWidth = document.documentElement.offsetWidth;
//get cols
var cols = parseInt(screenWidth / boxWidth);
//aim
father.style.width = cols * boxWidth + 'px';
father.style.margin = '0 auto';
//sonBox position
//define var
var heightArr = [], boxHeight = 0, minBoxHeight = 0, minBoxIndex = 0;
for (var i = 0; i < allBox.length; i++) {
//get every box height
boxHeight = allBox[i].offsetHeight;
//get heightArr
if (i < cols) {
heightArr.push(boxHeight);
allBox[i].style='';
} else {
//get minBoxHeight
minBoxHeight = Math.min.apply(this, heightArr);
//get minIndex
minBoxIndex = getMinBoxIndex(heightArr, minBoxHeight);
//sonBox position
allBox[i].style.position = 'absolute';
allBox[i].style.left = minBoxIndex * boxWidth + 'px';
allBox[i].style.top = minBoxHeight + 'px';
//refresh height
heightArr[minBoxIndex] += boxHeight;
}
}
}
/**
* 获取最小盒子
*/
function getMinBoxIndex(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
}