【发布时间】:2015-05-16 10:13:10
【问题描述】:
我想要做的是将导航栏中的<li> 元素隐藏到调整大小的下拉菜单中。
我试过了,我以这个有问题的菜单结束了。 http://i.imgur.com/1uJ7hbG.gif
这里是js:
$().ready(function () {
//we reconstruct menu on window.resize
$(window).on("resize", function (e) {
var parentWidth = $("#normal").parent().width() - 40;
var ulWidth = $(".menutohide").outerWidth();
var menuLi = $("#normal > li");
var liForMoving = new Array();
//take all elements that can't fit parent width to array
menuLi.each(function () {
ulWidth += $(this).outerWidth();
if (ulWidth > parentWidth) {
console.log(ulWidth);
liForMoving.push($(this));
}
});
if (liForMoving.length > 0) { //if have any in array -> move em to "more" ul
e.preventDefault();
liForMoving.forEach(function (item) {
item.clone().appendTo(".links-hidden");
item.remove();
});
}
else if (ulWidth < parentWidth) { //check if we can put some 'li' back to menu
liForMoving = new Array();
var moved = $(".links-hidden > li");
for (var i = moved.length - 1; i >= 0; i--) { //reverse order
var tmpLi = $(moved[i]).clone();
tmpLi.appendTo($("#normal"));
ulWidth += $(moved[i]).outerWidth();
if (ulWidth < parentWidth) {
$(moved[i]).remove();
}
else {
ulWidth -= $(moved[i]).outerWidth();
tmpLi.remove();
}
}
}
if ($(".links-hidden > li").length > 0) { //if we have elements in extended menu - show it
$(".menutohide").show();
}
else {
$(".menutohide").hide();
}
});
$(window).trigger("resize"); //call resize handler to build menu right
});
这里是html:
<nav class="navbar navbar-default" role="navigation">
<ul class="nav navbar-nav" id="normal">
<li><a href="#" class="first-child">Home</a></li>
<li><a href="#">News</a></li>
<li><a href="#">Download</a></li>
<li><a href="#">Twitch Live</a></li>
<li class="disabled"><a href="#">Ranking</a></li>
</ul>
<ul class="nav navbar-nav menutohide">
<li class="dropdown hidden-dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true">
<i class="fa fa-bars fa-fw"></i>
</a>
<ul class="dropdown-menu links-hidden" role="menu">
<!--Hidden links here-->
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<h6 class="hidden-xs">Bambini</h6>
<img src="http://placehold.it/250x250/000000"/>
<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Account info</a></li>
<li><a href="#">Logoff</a></li>
</ul>
</li>
</ul>
</nav>
【问题讨论】:
-
是否有任何具体原因在此使用 javascript 而不是 css 中的正确媒体查询?
-
@connexo : 使用媒体查询我无法达到我想要的效果,我还得重新编写
<li>元素。 -
除非您提供有效的小提琴,否则人们可能无法提供帮助。我什至不确定你想要实现什么,尽管我几乎可以肯定你的东西过于复杂了。
-
您能否通过创建小提琴分享您的代码。这将有助于我们调试问题。 :)
标签: javascript jquery html css twitter-bootstrap