1

我正在研究一个函数,它select从 html 中获取一个并用多列替换它ul- 这是一个列表,但有float:left;li级,所以列数基于计算(如果ul宽度为 600,li宽度为 200,我会显然有3列)。

这就是理论——最简单的部分。

示例:5 项,2 列

现在,当我从选择中获取数据时,我有这个列表:

 1
 2
 3
 4
 5

如果我只是将数组推入ul,它在屏幕上将如下所示:

1   2
3   4
5

但是对于用户/读者来说,当您不阅读时,它会更容易和更好,Left->Bottom而是Bottom->Left意味着您正在阅读直到列底部然后移动到下一列,而不是阅读行,然后是下一行。

所以我需要将列表转换为列:

1   4
2   5
3

所以,实际上ul将是这个顺序:

1   4   2   5   3

这需要使用可变列号,因为如果我们决定将 10 个项目添加到列表中,那么列数可能会更好。

对所需的运算符/周期和所涉及的数学有任何帮助吗?

谢谢

4

3 回答 3

2

我认为这是一个有趣的问题,所以我为你写了一个插件。我对其进行了一些测试,它似乎可以工作。让我知道这是否是你想要的!

http://jsbin.com/ocama/3/edit

http://jsbin.com/ocama/3

该算法非常简单,几乎可以归结为找到有多少行并根据该数字对列进行分组。

于 2010-02-18T17:51:42.153 回答
0

I made it :]

I did all the calulation. I also like Alex's solution, so I'll give him good answer and I add my solution here just for anyone looking for this kind of problem :)

var rows= 2; //editable number of rows

$('body').append('<ul id="fromselect"></ul>');
var o = $('select#tolist option');
var ul = $('ul#fromselect');

var total = o.size();
var onecol = Math.ceil(total / rows);
var index = 0; //index in o list

for (var j=1; j<=onecol;j++){
    for (var i=1;i<=rows;i++){
        if (!(i*j>total)){ //in last row, there might be less columns used
            index = (i-1)*onecol+j-1;
            ul.append('<li><a href="#">'+index +': '+
                      o.eq(index ).text()
                     +'</a></li>');
            //index is used more for debug, you can put
            //the index calculation in o.eq( * ) part
        }
    }
}
于 2010-02-18T18:26:03.690 回答
0

如果您知道有多少列,那么您将<li>通过一次跳过列表n来制作元素。因此,对于三列,您选择项目 0、3、6...,然后返回并选择 1、4、7,然后是 2、5、8。

于 2010-02-18T17:37:58.257 回答