问题
I'm writing a JQuery script which evenly spaces variable-sized horizontal navigation links inside a containing <ul>
, using margin-right. The algorithm is:
A: Get width of <ul>
container.
B: Add up widths of all <li>
items inside container.
C: Calculate right margin for each item except the last <li>
by subtracting B from A and dividing by the number of <li>
items in the container, minus 1.
But there is a flaw either in my algorithm or in my code, because the links are overflowing the container. Here is my code. Can you help please?
Thanks, -Northk
var containerWidth = $('#main-nav ul').width();
var linksWidth = 0;
$('#main-nav ul').children().each(function() {
linksWidth += $(this).width();
});
var linkSpacing = Math.floor((containerWidth - linksWidth) / ($('#main-nav ul').children().length - 1));
$('#main-nav ul').children().css('margin-right', linkSpacing + "px");
$('#main-nav ul').children().filter(":last").css('margin-right', 0);
And the HTML looks like:
<nav id="main-nav">
<ul>
<li>
<a href="#">home</a>
</li>
<li>
<a href="#">link-number-2</a>
</li>
</ul>
</nav>
回答1:
I just assumed some css rules but i believe this is what you were looking for. http://jsfiddle.net/TEDhb/
$('#main-nav ul li:not(:last-child)').css('margin-right', linkSpacing + "px");
回答2:
Hate to say this, but it works fine for me. Here is the jsFiddle for it (I assumed the minimal CSS). The top part of the code is your code (which works), the bottom commented-out part is my version (which adds nothing but is more efficient).
回答3:
You should divide by number of LIs, not by number of LIs-1.
来源:https://stackoverflow.com/questions/6513438/jquery-equally-spaced-navigation-links-inside-unordered-list-problem