javascript实现的手风琴折叠菜单效果
实现效果:
HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>手风琴效果</title> </head> <body> <div class="main"> <ul id="expand"> <li> <h3 class="h3-common">第一类目</h3> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </li> <li> <h3 class="h3-common">第二类目</h3> <ul> <li>5</li> <li>6</li> <li>7</li> </ul> </li> <li> <h3 class="h3-common">第三类目</h3> <ul> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul> </li> <li> <h3 class="h3-common">第四类目</h3> <ul> <li>12</li> <li>13</li> <li>14</li> <li>15</li> </ul> </li> </ul> </div> </body> </html>
CSS代码:
/* * by @Kevinの快乐时代 *2015/5/21 */ *{ margin: 0;padding: 0; } ul,li{ list-style: none; } .main{ width: 300px; color:#666; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin:auto; } .main ul li ul{ display: none; padding: 15px; background-color: #ecf0f1; } #expand li ul li { padding: 5px 0; border-bottom: 1px dotted #999; } .h3-common{ font-size: 15px; color: #fff; padding: 5px 22px; border-bottom: 1px dotted #e7e7e7; } .main h3{ background: url(http://www.iconfont.cn/uploads/fonts/font-155705-.png?color=ecf0f1&size=20) no-repeat #00bb9c left center; } .main h3.active{ background: url(http://www.iconfont.cn/uploads/fonts/font-69084-.png?color=ecf0f1&size=20) no-repeat #ea8010 left center; } .li_active{ background-color: #56abe4; color: #fff; text-align: center; border-radius: 3px; }
javascript代码:
var oExpand=document.getElementById(‘expand‘); var ah3=oExpand.getElementsByTagName(‘h3‘); var aUl=oExpand.getElementsByTagName(‘ul‘); var aLi=null; var arrLi=[]; for(var i=0;i<ah3.length;i++){ ah3[i].index=i; ah3[i].onclick=function(){ var current_num=this.index;//添加自定义索引值 for(var i=0;i<aUl.length;i++){ //没被选中的ul折叠起来 if(ah3[i] != this){ ah3[i].className="h3-common"; aUl[i].style.display="none"; } } //展开,收起 if(!ah3[current_num].classList.contains(‘active‘)){ ah3[current_num].classList.add(‘active‘); aUl[current_num].style.display=‘block‘; }else{ ah3[current_num].classList.remove(‘active‘); aUl[current_num].style.display=‘none‘; } } } //添加数组 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]); } } for(var i=0;i<arrLi.length;i++){ arrLi[i].onclick=function(){ //初始化其他li for(var i=0;i<arrLi.length;i++){ if(arrLi[i] !=this){ arrLi[i].className=‘‘; } } //元素本身的点击选中,再点击消失;.li_active是选中时的状态 if(!this.classList.contains(‘li_active‘)){ this.classList.add(‘li_active‘); }else{ this.classList.remove(‘li_active‘) } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。