我有一个动态创建的导航,但无法创建用于导航的父/子列表。
我想根据可用空间在列表末尾添加一个名为“更多...”的链接。然后将所有剩余元素显示为更多...的子元素...
例如,如果我有元素 list1、list2、list3、..... list10。
它将显示为 list1、list2、list3、more...,其余链接将是 more...的子链接
我尝试为此创建一个脚本,我认为我已经非常接近了。但我有以下两个问题:
- 如何在子列表周围添加 UL。
- 有时“更多...”会断到下一行。
以下是我的JS代码:
$(document).ready(function() {
var nav = $('ul');
var more = '<li><a href="#">More...</a></li>';
nav.prepend( more );
var availableSpace = nav.innerWidth();
var list = 0;
var countedSpace = 0;
$('li').each(function(){
var current = $(this);
countedSpace = countedSpace+current.outerWidth();
if (countedSpace < availableSpace) {
list++;
}
})
var showInList = list; //Space available for xx no. of items.
var newList = [];
// Start at 2, don't include dynamically added more link.
for (i = 2; i < showInList; i++) {
newList.push($(nav).find("li:nth-child("+i+")"));
}
newList.push(more);
var childList = [];
for (i = showInList; i <= nav.children().length; i++) {
childList.push($(nav).find("li:nth-child("+i+")"));
}
//nav.empty();
nav.html(newList);
$(nav).find("li:last-child").append(childList);
});
最佳答案
1。如何在子列表周围添加 UL。
尝试创建一个 jquery UL 对象,然后将 li 项附加到它。像这样:
var ulChildren = $("<ul/>").append(childList);
$(nav).find("li:last-child").append(ulChildren);
2。有时“更多...”会断到下一行。
发生这种情况是因为 li 子项可见并且堆叠在右侧,请尝试添加
li ul{
display:none;
}
在第 1 步之后测试正确的布局。
这是 JSFiddle 上的上述示例,单击“更多...”以切换子级可见性
关于javascript - 将导航包裹在子导航中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27000785/