JQuery在无序列表问题中等距离导航链接 [英] JQuery equally spaced navigation links inside unordered list problem
问题描述
我正在编写一个JQuery脚本,它使用margin-right在包含< ul>
的内部均匀分布可变大小的水平导航链接。算法是:
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:获取的宽度< ul>
容器。
B:在容器内添加所有< li>
项目的宽度。
B: Add up widths of all <li>
items inside container.
C:通过从A中减去B并除以< li>的数量,计算除最后
容器中的项目减1。< li>
之外的每个项目的右边距。
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?
谢谢你,
-nk先生
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);
HTML看起来像:
<nav id="main-nav">
<ul>
<li>
<a href="#">home</a>
</li>
<li>
<a href="#">link-number-2</a>
</li>
</ul>
</nav>
推荐答案
我刚刚假设了一些css规则,但我相信这是你在找什么
http://jsfiddle.net/TEDhb/
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");
这篇关于JQuery在无序列表问题中等距离导航链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!