先給大家看效果圖:
先看頁面程式碼,清單的巢狀:
<div id="menuDiv"> <ul id="menu"> <li class="parentLi"> <span>B</span> <ul class="childrenUl"> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> </ul> </li> <li class="parentLi"> <span>B</span> <ul class="childrenUl"> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> </ul> </li> <li class="parentLi"> <span>B</span> <ul class="childrenUl"> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> <li class="childrenLi"><span>C</span></li> </ul> </li> </ul> </div>
css 程式碼,主要設定背景色和子選單左邊框的樣式,設定懸浮和選取的樣式,開始設定子選單不顯示(透過 js 設定點擊之後再顯示):
#menuDiv{ width: 200px; background-color: #029FD4; } .parentLi { width: 100%; line-height: 40px; margin-top: 1px; background: #1C73BA; color: #fff; cursor: pointer; font-weight:bolder; } .parentLi span { padding: 10px; } .parentLi:hover, .selectedParentMenu { background: #0033CC; } .childrenUl { background-color: #ffffff; display: none; } .childrenLi { width: 100%; line-height: 30px; font-size: .9em; margin-top: 1px; background: #63B8FF; color: #000000; padding-left: 15px; cursor: pointer; } .childrenLi:hover, .selectedChildrenMenu { border-left: 5px #0033CC solid; background: #0099CC; padding-left: 15px; }
接下來就是點選事件的程式碼:
$(".parentLi").click(function(event) { $(this).children('.childrenUl').slideToggle(); }); $(".childrenLi").click(function(event) { event.stopPropagation(); $(".childrenLi").removeClass('selectedChildrenMenu'); $(".parentLi").removeClass('selectedParentMenu'); $(this).parents(".parentLi").addClass('selectedParentMenu'); $(this).addClass('selectedChildrenMenu'); });
要注意的是清單嵌套,會導致事件冒泡,所以在子選單的點擊事件裡面要組織冒泡,event.stopPropagation();
以上程式碼很簡單,程式碼就是註釋,jquery手風琴選單就實現了。需要的朋友快來參考下。