我有同樣的問題,我無法找到我的問題的任何解決方案。經過幾個小時的試圖輕鬆解決,我終於爲我創建瞭解決方案。它主要是用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