<style> * { margin: 0; padding: 0; } li { list-style-type: none; } .classify>ul>li { width: 200px; text-indent: 20px; background: blue; } .classify>ul>li>ul>li { background: #fff; } .classify>ul>li ul { display: none; } .active { /*!important优先级最高,必不可少,否则执行上一行代码display:none隐藏ul*/ display: block!important; } </style> <script> window.onload = function () { var li = document.querySelectorAll(".classify>ul>li"), ul = document.querySelectorAll(".classify>ul>li>ul"), index = null; for (var i = 0, len = li.length; i < len; i++) { li[i].index = i; li[i].onclick = function () { for (var j = 0, len2 = ul.length; j < len2; j++) { //除了当前显示的ul添加active,其他ul都删除active if (this.index != j) ul[j].className = ""; } //第一次点击时添加active,显示ul if (ul[this.index].className == "") ul[this.index].className = "active"; else //第二点击时删除active,隐藏ul ul[this.index].className = ""; } } } </script> </head> <body> <div class="classify"> <ul> <li> <p>1</p> <ul> <li>11</li> <li>12</li> <li>13</li> </ul> </li> <li> <p>2</p> <ul> <li>22</li> <li>2</li> <li>2</li> </ul> </li> <li> <p>3</p> <ul> <li>3</li> <li>3</li> <li>3</li> </ul> </li> <li> <p>4</p> <ul> <li>4</li> <li>4</li> <li>4</li> </ul> </li> </ul> </div> </body> </html>
转载于:https://www.cnblogs.com/xingkongly/p/7603678.html