2

我运行了一段简单的 jQuery 来为我的列表项分配宽度:

    $(subMenu).each( function() {
        var noLi        = $(this).children('li').length,
            itemSize    = (10/noLi)*10;
        $(this).children('li').each( function() {
            $(this).css('width', itemSize +'%');
        });
    });

我知道在这种情况下总是少于 10 个列表项,所以我通过简单的itemSize计算来生成百分比宽度。但是,如果添加了更多项目,整个事情就会失败,布局也不会像预期的那样。

我也相信这可能不是首先实现这一目标的最有效方法,但我不确定更好的方法。有人可以指出我正确的方向吗?

4

2 回答 2

1

首先,您不需要对您将拥有多少物品做出任何假设。如果您只想将 100% 宽度分成 x 个项目,您可以简单地使用100 / x.

此外,您不需要嵌套.each。jQuery 会自动执行此操作。

$(subMenu).each(function() {
    var items = $(this).children('li');
    var itemSize = 100 / items.length;
    items.css('width', itemSize +'%');
});
于 2013-07-30T18:11:23.583 回答
1

你的意思是 itemSize 变大了?如果是这样,您可以这样做:

itemSize = Math.min(100, (10/noLi)*10); // Get smallest value of the two. 100 is the max now

关于添加尺寸,您可以将代码替换为:

 $(this).children('li').css('width', itemSize +'%'); // no need for each

结合起来是:

$(subMenu).each( function() {
    var $AllLi  = $(this).children('li'); // Save'm all for later access
    var noLi    = $AllLi.length; // we saved all selected li´s so we dont need to reselect
    itemSize    = Math.min(100, (10/noLi)*10);
    $AllLi.css('width', itemSize +'%'); // no need for each
});

另一种方法可能更好,使用 css:

<style>
    ul{
        width: 100%; 
        display: table-row;
    }
    li{
        display: table-cell;
    }
    li:gt(10){
        display: none;
    }
</style>
<ul>
    <li>li part</li>
    <li>li part</li>
    <li>li part</li>
    <li>li part</li>
</ul>
于 2013-07-30T17:59:17.760 回答