9

我有一个标准的UL如下:

<ul>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
</ul>

我正在尝试找到一种快速有效的方法来计算所有 LI 标签的组合。目前我有:

var width = 0;

$('ul li').each(function() {
 width += $(this).outerWidth();
});

我只是想知道是否有一种更快的方法可以在不使用循环的情况下获得相同的结果?

谢谢你的帮助!

4

3 回答 3

5

To get exactly what you're after, no there's not. This just isn't a case that fits well with existing functions, a loop like you have it is the quickest way. There is talk of putting an .childWidth() or something into core...but I wouldn't hold my breath :)

The other answers would include the parent's width including extra space, that's usually not what you're after, so for now...stick with the loop like you have. Anything shorter that will be added will be just about guaranteed do the same amount of work (possibly identical code as well) underneath anyway.

于 2010-06-17T10:48:18.833 回答
0

您可以获得 ul 元素本身的宽度,但这会给您包括项目符号和边距在内的宽度:

var width = $("ul").outerWidth();
于 2010-06-17T09:56:50.603 回答
0

如果这是一个菜单并且项目彼此相邻(而不是在下方),请尝试$('ul').outerWidth().

[编辑] 如果 的宽度ul是固定的,则找到列表的最后一个元素并查看其右侧偏移量。由于偏移量总是相对于父元素,你所要做的就是添加offsetLeftoffsetWidth获取所有子元素的总宽度。

于 2010-06-17T09:57:11.570 回答