This article implements the method of determining whether the menu under the title is displayed when clicking on the title. If it is displayed, it will be hidden. If it is hidden, it will be displayed. The specific code is as follows
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{margin:0; padding:0; font-size:13px; list-style:none;} .menu{width:210px; margin:50px auto; border:1px solid #ccc;} .menu p{height:25px; line-height:25px; font-weight:bold; background:#eee; border-bottom:1px solid #ccc; cursor:pointer; padding-left:5px;} .menu div ul{display:none;} .menu li{height:24px; line-height:24px; padding-left:5px;} </style> <script type="text/javascript"> window.onload=function(){ // 将所有点击的标题和要显示隐藏的列表取出来 var ps = document.getElementsByTagName("p"); var uls = document.getElementsByTagName("ul"); // 遍历所有要点击的标题且给它们添加索引及绑定事件 for(var i = 0, n = ps.length; i <n; i += 1){ ps[i].id = i; ps[i].onclick = function(){ for(var j = 0; j < n ; j += 1){ uls[j].style.display = "none"; } uls[this.id].style.display = "block"; } // 获取点击的标题上的索引属性,根据该索引找到对应的列表 } // 判断该列表,如果是显示的则将其隐藏,如果是隐藏的则将其显示出来 } </script> </head> <body> <div class="menu" id="menu"> <div> <p>Web前端</p> <ul style="display:block"> <li>JavaScript</li> <li>DIV+CSS</li> <li>jQuery</li> </ul> </div> <div> <p>后台脚本</p> <ul> <li>PHP</li> <li>ASP.net</li> <li>JSP</li> </ul> </div> <div> <p>前端框架</p> <ul> <li>Extjs</li> <li>Esspress</li> <li>YUI</li> </ul> </div> </div> </body> </html>
Example effect:
The above is the JavaScript telescopic menu bar implementation code shared with you. I hope it will be helpful to your learning.