3

You can see the problem on http://jsfiddle.net/6gnAF/1/

I've little problem with my list elements.

I'm using very simple unordered list like;

<div>
  <ul>
    <li class='button'>Element 1</li>
    ...
    <li class='button'>Element N</li>
  </ul>
</div>

(Number of list elements, N, varies on every page.)

The div which contains the ul is 696 px width. List elements, li, are horizontally aligned, and when they reach end of div's width, they contiues on new line.

What I wanted to adding class .left the first li of every line, and class .right to the last one.

    $('li').each(function() {
        var liWidthOut = $(this).width();
        totalWidth += liWidthOut;
        if (totalWidth >= divWidth) {
            $(this).addClass("left");
            $(this).prev().removeClass("middle").addClass("right");
            totalWidth = liWidthOut;
        }
        else {
            $(this).addClass("middle");
        }
     });

I managed that with Jquery, but I've a little problem.

You can see the problem on http://jsfiddle.net/6gnAF/1/

The problem is, .left and .right classes change the width of li elements which are added to, so some times they create new lines, and last li elements become first one which have .right class, instead of .left.

How can I fix this?

(Sorry for the grammatically errors)

4

3 回答 3

5

我更改了跟踪top位置而不是计算宽度的方法,似乎工作正常。使用width()填充和边框以及诸如此类的东西不太可靠。

$('li')
    // Add classes first, so we calculate on the right styles
    .addClass("middle")
    .addClass("button")
    .each(function() {
        // Compare with last position
        if (lastPos != $(this).position().top) {
            $(this).removeClass("middle").addClass("left")
                .prev().removeClass("middle").addClass("right");
        }
        // Store last position
        lastPos = $(this).position().top;
    });

http://jsfiddle.net/2qydM/6/

于 2012-10-25T14:31:36.820 回答
4

您的代码大部分是正确的,只有两个使其出错的挑剔:

  1. 使用var liWidthOut = this.offsetWidth;而不是var liWidthOut = $(this).width();后者为您提供内部文本的宽度,而不是像添加填充一样offsetWidth

  2. .button在开始循环和计算宽度之前应用类,因为.button样式会影响元素的宽度,你必须首先应用它,这样你的计算就不会在以后失败。

请参阅纠正了这两件事的代码的工作演示

于 2012-10-25T15:07:30.977 回答
0

Would it be possible to separate these lists into seperate lists?

If so you could use :nth-child or :last-child

于 2012-10-25T14:38:22.897 回答