泛化代码以处理任意数量的列

Generalizing code to work with any number of columns

本文关键字:任意数 处理 代码 泛化      更新时间:2023-09-26

如何将以下代码泛化,使其适用于任何数量的颜色?

if (totalColls==4){
    $(aclst).eq(0).css({"top":itlh*0+"px", "left":itlwi*0+"px"});
    $(aclst).eq(1).css({"top":itlh*0+"px", "left":itlwi*1+"px"});
    $(aclst).eq(2).css({"top":itlh*0+"px", "left":itlwi*2+"px"});
    $(aclst).eq(3).css({"top":itlh*0+"px", "left":itlwi*3+"px"});
    $(aclst).eq(4).css({"top":itlh*1+"px", "left":itlwi*0+"px"});
    $(aclst).eq(5).css({"top":itlh*1+"px", "left":itlwi*1+"px"});
    $(aclst).eq(6).css({"top":itlh*1+"px", "left":itlwi*2+"px"});
    $(aclst).eq(7).css({"top":itlh*1+"px", "left":itlwi*3+"px"});
    $(aclst).eq(8).css({"top":itlh*2+"px", "left":itlwi*0+"px"});
    $(aclst).eq(9).css({"top":itlh*2+"px", "left":itlwi*1+"px"});
    $(aclst).eq(10).css({"top":itlh*2+"px", "left":itlwi*2+"px"});
    $(aclst).eq(11).css({"top":itlh*2+"px", "left":itlwi*3+"px"});
}

这应该适用于任何数量的行或列。

    jQuery $(aclst).each()函数迭代所有元素,并为回调函数提供适当的索引和DOM节点。
  • 数学。floor(index/totalColls) call返回从0开始的行号。
  • index % totalColls调用返回列号,从0开始。

下面是迭代所有元素时的样子:

$(aclst).each(function(index, element) {
    $(element).css({
        "top" : (itlh * Math.floor(index / totalColls)) + "px",
        "left": (itlwi * index % totalColls) +"px"
    });
});