<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS——伸縮菜單3</title>
<style>
ul , h2 { padding:0; margin:0; }
li { list-style:none; }
#list { width:240px; border:1px solid #ccc; border-top:none; margin:0 auto; }
#list h2 { font-size:14px; border-top:1px solid #ccc; height:30px; line-height:30px; text-indent:20px; background:url(images/arr1.gif) no-repeat 5px center #eee; color:#000; cursor:pointer;}
#list .active { background:url(images/arr2.gif) no-repeat 5px center #ddd; color:#000; }
#list ul { display:none; }
#list ul li { line-height:24px; border-top:1px solid #ccc; text-indent:24px; }
#list ul .hover { background:#f4f4f4; }
</style>
<script>
window.onload = function(){
var oUl = document.getElementById('list');
var aH2 = oUl.getElementsByTagName('h2');
var aUl = oUl.getElementsByTagName('ul');
aLi = null;
var arrLi = [];
//點擊伸縮
for(var i = 0; i<aH2.length; i++){
aH2[i].index = i;
aH2[i].onclick = function(){
//循環所有H2,隱藏不是當前的ul及H2的className
for(var i = 0; i<aH2.length; i++){
if(i != this.index){
aUl[i].style.display = '';
aH2[i].className = '';
}
}
if(this.className == ''){
aUl[this.index].style.display = 'block';
this.className = 'active';
}else{
aUl[this.index].style.display = '';
this.className = '';
}
};
}
//二次循環生成所有子li,然後將生成的所有元素保存到數組中
for(var i = 0; i<aUl.length; i++){
aLi = aUl[i].getElementsByTagName('li');
for(var j = 0; j<aLi.length; j++){
arrLi.push(aLi[j]);
}
}
//點擊當前子li,改變顏色
for(var i= 0; i<arrLi.length; i++){
arrLi[i].onclick = function(){
for(var i=0; i<arrLi.length; i++){
arrLi[i].className = '';
}
this.className = 'hover';
}
}
};
</script>
</head>
<body>
<ul id="list">
<li class="lis">
<h2>我的好友</h2>
<ul>
<li>張三</li>
<li>張三</li>
<li>張三</li>
<li>張三</li>
</ul>
</li>
<li class="lis">
<h2>企業好友</h2>
<ul>
<li>李四</li>
<li>李四</li>
<li>李四</li>
<li>李四</li>
<li>李四</li>
</ul>
</li>
<li class="lis">
<h2>黑名單</h2>
<ul>
<li>阿貓</li>
<li>阿狗</li>
</ul>
</li>
</ul>
</body>
</html>
在前面的基礎上,修改成摺疊菜單
其思路:
循環遍歷所有的H2,判斷i是否等於當前的索引值