Javascript to turn an unordered list into multiple columns

后端 未结 7 709
忘掉有多难
忘掉有多难 2020-12-29 11:55

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 th

7条回答
  •  无人及你
    2020-12-29 12:46

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

    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.

    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);
            }
        });
    });
    

提交回复
热议问题