开发者

Calculating total width of all list items?

开发者 https://www.devze.com 2023-01-04 06:38 出处:网络
I have a standard UL as follows: <ul> <li><a href=\"\">Link</a></li> <li><a href=\"\">Link</a></li>

I have a standard UL as follows:

<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>

I am trying to find a quick & efficient way to calculate the combined with of all the LI tags. Currently I have:

var width = 0;

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

I'm just 开发者_运维知识库wondering if there is a quicker way to get the same result without using a loop?

Thanks for your help!


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.


You could get the width of the ul element itself, but that would give you the width including the bullets and margins:

var width = $("ul").outerWidth();


If this is a menu and the items are next to each other (and not below), try $('ul').outerWidth().

[EDIT] If the width of the ul is fixed, then locate the last element of the list and have a look at its right offset. Since offset is always relative to the parent element, all you have to do is to add offsetLeft and offsetWidth to get the total width of all children.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号