Javascript将无序列表转换为多列 [英] Javascript to turn an unordered list into multiple columns

查看:184
本文介绍了Javascript将无序列表转换为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有一个简单的方法(良好支持)css做到这一点。我正在寻找一个javascript解决方案,最好是jQuery。

There doesn't seem to be an easy way in (well supported) css to do this. I'm looking for a javascript solution, preferably jQuery.

我有一个无序的列表,像这样:

I have an unordered list like this:

<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>        
    ...etc
</ul>

我想让每一列有一个高度,例如四个项目,垂直填充,而不是像css float:

I want each column to have a height for example four items and fill vertically rather than horizontally like a css float:

A     E
B     F
C
D


推荐答案

Doug的解决方案很好,如果你想将列表分成子列表。

Doug's solution is nice if you want to split the list up into sub lists.

相反,我选择了定位列表元素而不改变dom。
这是一个有点凌乱,基本上它在每个元素放置左边距,这是列数乘以列宽。
这将导致一个楼梯布局,所以下一步是添加一些负顶部边距,使每个元素到顶部。

Instead I chose to position the list elements without changing the dom. This is a bit messy, basically it puts a left margin on each element which is the column number multiplied by the column width. This will result in a staircase layout so the next step was to add some negative top margin to bring each element up to the top.

基本上这显示为网格。我使用这个下拉菜单,所以它工作得很好。如果您需要每个列表项具有动态高度,请避免使用此选项。可以将col_height变量设置为最大项的高度,以使代码更具有一般性的用途。

Basically this displays as a grid. I am using this for drop down menus so it worked well. Avoid using this if you need each list item to have a dynamic height. The col_height variable could be set to the height of the largest item to make the code a bit more general purpose.

var col_max_height = 6; //Max Items per column
var col_width = 200; //Pixels
var col_height = 33; //Pixels
$('.header ul li ul').each(function() {
    $(this).find('li').each(function(index){
        column = parseInt(index/col_max_height);
        $(this).css('margin-left', column * col_width + 'px')
        if(column > 0) {
            $(this).css('margin-top', (index - (col_max_height * column)  + 1) * -col_height + 'px').addClass('col_'+column);
        }
    });
});

这篇关于Javascript将无序列表转换为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆