如果你想自己做(它的樂趣,寫的東西自己):
我添加的#tree
一個ID爲根<ul>
,並在<span>
包裹1級<li>
S的文本:
<ul id="tree">
<li>
<span>parent1</span>
<ul>
<li>child11</li>
<li>child12</li>
</ul>
</li>
<li>
<span>parent2</span>
<ul>
<li>child21</li>
<li>child22</li>
</ul>
</li>
</ul>
要應用點左右到父元素箭,有背景的創建兩個CSS類,例如,(你需要找到其他地方的背景圖片,或使自己):
.opened > span {
background: url('arrow_pointing_down.png') left top;
color: #0a0; /* just to make it easy to know which class it has */
}
.closed > span {
background: url('arrow_pointing_right.png') right top;
color: #00a; /* just to make it easy to know which class it has */
}
要隱藏所有的子元素時,頁面加載...
$('#tree > li').addClass('closed');
// hide the level 2 ul's
$('#tree > li ul').hide();
在點擊處理
然後:
$("#tree > li > span").click(function (event) {
event.preventDefault();
// swap the opened and closed classes
$(this).parent().toggleClass('opened closed');
// toggle the level 2 ul instead of li
$(this).parent().find("ul").toggle();
});
工作演示在這裏:http://jsfiddle.net/cTLGN/
附加:
此演示代碼不使用對jQuery對象的緩存引用,以便於閱讀。在現實中,而不是這樣做的:
$(this).parent().toggleClass('opened closed');
$(this).parent().find("ul").toggle();
...一個應該做的:
var parent = $(this).parent(); // search the DOM once for this' parent, and remember it
parent.toggleClass('opened closed');
parent.find("ul").toggle();
..因爲每次你使用jQuery的$()構造函數時,它需要搜索直通整個DOM,從而可以如果你反覆做這件事情會很貴。
你在找什麼是手風琴。使用jQuery創建手風琴菜單非常簡單。網上有很多教程。 – otherDewi
您還可以查看[** Jquery EasyUI Tree **](http://www.jeasyui.com/demo/main/?plugin=Tree&theme=default&dir=ltr&pitem=)插件。查看** Async Tree **演示。 – th1rdey3