How to get css3 multi-column count in Javascript

前端 未结 3 914
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 21:39

We\'re using the new css3 multi-column layout properties to get our text into newspaper columns. Each column gets a fixed width, and the column-count defaults to \"auto\", w

相关标签:
3条回答
  • 2020-12-05 22:24

    Try this:

    $.fn.howMuchCols = function(){
      return Math.round($(this).find(' :last').position().left - $(this).position().left / $(this).outerWidth()) +1;
    };
    
    $('.my-stuff-with-columns').howMuchCols();

    Code explanation:

    This code will create a function 'howMuchCols ' to each jQuery element.

    You can't get the width of a element with columns using the conventional way, because his width is used to define each inner column size. To know how many columns the element have inside, you need to get his real width and divide by the columns size, then you will have the column amount.

    The way to get the real width is to sum the X offset of the last child element of the columns container with it width, then, subtract it with the sum of the column container X offset.

    In the code, I have added the size of one column after make the subtraction and division rather than use the pixel unit before the division (it does not make difference).

    The Math.round must be there because not always the container size will be exactly divisible by his inner columns width.

    0 讨论(0)
  • 2020-12-05 22:29

    could you set a class to each column such as class="another-column" and then use Jquery to select the classes and iterate them.

    var count = 0;
    $('.another-column').each(function(){
        count++;
    });
    

    Warning, this is untested. If you could supply with some html/css3 code I could test it on jsfiddle

    0 讨论(0)
  • 2020-12-05 22:37

    The secret is to put a small marker at the end of the content. You can programmatically add an empty span:

    <span id="mymarker"></span>
    

    then grab the span using a jquery $("#mymarker") and get the "left" property. Divide that number by the width of the columns (adjusted for column-gap), and that will tell you what column this last element is in. Math.ceil() on the value and you have the column count.

    0 讨论(0)
提交回复
热议问题