我有同样的问题,我无法找到我的问题的任何解决方案。经过几个小时的试图轻松解决,我终于为我创建了解决方案。它主要是用JQuery制作的,但我认为,你可以很容易地将其修改为另一个js框架。我不是javascript专家,所以代码可能不会最优化。
HTML(仅用于说明)
<ul id="nav">
<li class="level-top">
<a href="#"><span>Item 1</span></a>
<ul class="level0">
<li class="level1">
<a href="#"><span>Item 2</span></a>
</li>
<li class="level1">
<a href="#"><span>Item 3</span></a>
</li>
</ul>
</li>
</ul>
CSS(仅用于说明)这里解决
ul#nav { display:block; }
li.level-top { position:relative; float:left; width:120px; height:50px; }
li.level-top a { display:block; height:50px; line-height:50px; }
ul.level0 {
position:absolute;
top:50px;
left:0;
padding:9px 0;
border:3px solid #CCC;
width:240px;
display:none;
}
li.level-top:hover ul.level0 { display:block; }
li.level1 { position:absolute; width:120px; }
li.level1.odd { left:0; }
li.level1.even { right:0; }
JS 我的主要问题。具有级别0的UL元素通常隐藏。我们需要将其显示在屏幕外并将两列的顶部定位放回原处并返回。
(function($){ // start jquery
$(document).ready(function(){ // domready
$("#nav > li > ul > li:nth-child(odd)").addClass('odd'); // This add class="odd" to every odd li in ul.level0
$("#nav > li > ul > li:nth-child(even)").addClass('even'); // This add class="even" to every even li in ul.level0
$('ul.level0').each(function(index) { // get all ul elements with level0 class
$(this).css('top', '-5000px').css('display', 'block'); // hide out of screen before changes and make display:block to possiblity of get heights of elements
var topPadding = parseInt($(this).css('padding-top')); // get padding-top (only numeric value) of ul element
var leftHeight = 0; // start left column from 0 (top position)
$(this).children('li.level1.odd').each(function(index) { // get odd elements
var $liOuterHeight = $(this).outerHeight(true); // get height of li element (height with padding, border and margin)
$(this).css('top', (leftHeight+topPadding)+'px'); // set top position of li element
leftHeight += $liOuterHeight; // modify height of left column
});
var rightHeight = 0; // start right column from 0 (top position)
$(this).children('li.level1.even').each(function(index) { // get even elements
var $liOuterHeight = $(this).outerHeight(true); // get height of li element (height with padding, border and margin)
$(this).css('top', (rightHeight+topPadding)+'px'); // set top position of li element
rightHeight += $liOuterHeight; // modify height of right column
});
$(this).height(rightHeight > leftHeight ? rightHeight : leftHeight).css('top', '').css('display', ''); // set height to ul element and change back all css changes (positioning + display)
});
}); // end of domready
})(jQuery); // end of jquery
我希望它有助于某人。这是为通常隐藏的菜单制作的。我想,你可以修改它来做其他事情。这并不难。
即使有CSS选择器来执行此操作,您也可以使用JQuery将'float:left;'添加到even和'float:right'中,以便奇数:'.class:nth-of-type(even);'或'.class:第n种类型(奇数);' – 2011-02-27 22:01:23