js——九宫格算法(定位) 瀑布流布局

九宫格算法
这里写图片描述
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;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值