这种打开关闭的菜单制作方法和之前的子菜单显示的制作方法相似,首先使其子菜单部分设置隐藏,当点击主菜单时,子菜单出现,当再点击主菜单时,子菜单关闭。
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> *{ margin:0px auto; padding:0px;} #cds{ 350px; height:200px; margin:20px auto;} .cd{ 300px; height:50px; border:1px #FF0000 solid; text-align:center; line-height:50px; vertical-align:middle; font-size:18px;} .cd:hover{ cursor:pointer;} .zcd{ 300px; height:153px; border:1px #FF0000 solid; text-align:center; line-height:50px; vertical-align:middle; font-size:18px;} .cai{ 300px; height:50px; border-bottom:1px #FF0000 solid;} .cai:hover{ cursor:pointer;} </style> </head> <body> <div id="cds"> <div class="cd">菜单一</div> <div class="zcd" style="display:none"> <div class="cai">11</div> <div class="cai">12</div> <div class="cai">13</div> </div> <div class="cd">菜单二</div> <div class="zcd" style="display:none"> <div class="cai">21</div> <div class="cai">22</div> <div class="cai">23</div> </div> <div class="cd">菜单三</div> <div class="zcd" style="display:none"> <div class="cai">31</div> <div class="cai">32</div> <div class="cai">33</div> </div> </div> </body> <script type="text/javascript"> var a = document.getElementsByClassName("cd"); for(var i=0; i<a.length; i++){ a[i].onclick=function(){ if(this.nextSibling.nextSibling.style.display=="block"){ this.nextSibling.nextSibling.style.display = "none"; }else{ this.nextSibling.nextSibling.style.display = "block"; } } } </script> </html>
在函数中,加入if语句,使其在菜单打开的状态时再点击可以关闭子菜单。