Javascript to turn an unordered list into multiple columns

后端 未结 7 649
忘掉有多难
忘掉有多难 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:45

    You will want to use a combination of CSS and jQuery, but in theory it is very simple. Render a complete single list in HTML, then provide a wrapper via jQuery and split the list up as desired. The following function does just that. Be sure to use a more specific selector than just ul when actually using the script. An id would be ideal.

    View demo here.

    jQuery(function ($) {
      var size = 4,
          $ul  = $("ul"),
          $lis = $ul.children().filter(':gt(' + (size - 1) + ')'),
          loop = Math.ceil($lis.length / size),
          i    = 0;
    
      $ul.css('float', 'left').wrap("
    "); for (; i < loop; i = i + 1) { $ul = $("
      ").css('float', 'left').append($lis.slice(i * size, (i * size) + size)).insertAfter($ul); } });

提交回复
热议问题