使用jQuery修改列表(<ul> <li>)</li> </ul>

时间:2011-08-14 11:49:31

标签: javascript jquery html css

我在PHP中生成了<UL><LI>的列表。该脚本从上到下生成:

<ul class="list_test">
<li>111
</li>
<li>222
</li>
<li>333
</li>
<li>444
</li>
<li>555
</li>
<li>666
</li>
<li>777
</li>
<li>888
</li>
<li>999
</li>
<li>1010
</li>
</ul>

现在它们呈现如下:

111
222
333
444
555
666
777
888
999
1010

如何将这些组合成组?

让我们说,我希望它们可以呈现为:

111 555 999
222 666 1010
333 777 etc
444 888

我该怎么做?

我想只使用Javascript而不是修改PHP。我考虑过添加一个div,例如,100 px高,这将包裹在右边......

jsfiddle: http://jsfiddle.net/hf2PL/

2 个答案:

答案 0 :(得分:3)

我在这里嘲笑了一个解决方案:http://jsfiddle.net/eqvc4/

它使用绝对定位将<li>元素重新排列到列中。 JavaScript代码如下:

var $ul = $('ul'),
    $li = $ul.children(),
    cols = 3,
    rows = Math.ceil($li.length / cols),
    height = rows * 1.2,
    width = cols * 5;

$ul.css({ height: height+'em', width: width+'em' });
$li.each(function(index) {
    var col = Math.floor(index / rows),
        row = index % rows,
        left = col * 5,
        top = row * 1.2;

    $(this).css({ left: left+'em', top: top+'em' });
});

它还需要以下CSS:

ul {
    position: relative
}

li {
    width: 5em;
    height: 1.2em;
    position: absolute;
}

答案 1 :(得分:0)

some fine jQuery plugins for columnizing stuff

但是,对于咯咯笑,这是一个动态宽度的方法(列使用所有容器宽度)。

See it in action at jsFiddle.

基本CSS:

.list_test li {
    line-height: 1.5em; /* Linked to code, for now. */

    /* Clear the default margins & padding
       so we can style the list from scratch */
    margin: 0;
    padding: 0;
}

<强> JavaScript的:

$(function () {
    columnize (".list_test", "li", 3);
} );

//--- All items must be equal height!  For now.

function columnize (contSelect, itemSelect, numColumns) {
    var container   = $(contSelect);
    var items       = container.children (itemSelect);
    var maxWidth    = container.width ();

    //--- Set defaults.
    var numColumns  = numColumns  ||  2;

    //--- Add the appropriate classes to the items.
    var itemsPerCol = Math.ceil (items.length / numColumns);
    items.each ( function (J) {
        var colNum  = Math.floor (J / itemsPerCol) + 1;
        $(this).addClass ('COLMZ_Column_' + colNum);

        //--- Is this the top of a column (except the first)?
        if (J  &&  ( (J / itemsPerCol) + 1 ) == colNum)
            $(this).addClass ('COLMZ_Reset');
    } );

    //--- Write the custom styles.
    var marginReset = itemsPerCol * 1.5 // Based on style, for now.
    var columnWidth = Math.floor (maxWidth / numColumns)
    var styleStr    = contSelect + ' .COLMZ_Reset {margin-top: -' + marginReset + 'em;}\n';

    for (var J = 0;  J < numColumns;  ++J) {
        var margAdj = columnWidth * J;
        styleStr   += contSelect + ' .COLMZ_Column_' + (J+1) + '{margin-left: ' + margAdj + 'px;}\n';
    }
    $('<style type="text/css"></style>').text (styleStr).appendTo ('body');
}