1.html
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <style> body{ user-select:none; } ul,li{list-style: none;margin:0;padding: 0;} .tabs{width:500px;margin:0 auto;background: #d69b9b;color: #fff;padding: 0 20px;} .tabs-cell{margin: 20px 0;} .tabs-cell ul{display: none;} .tabs-cell-2{margin-left: 45px;} .tabs-cell-2 li{padding: 7px 0;background: gainsboro;margin: 4px 0;} </style> </head> <body> <div class="tabs"> <div class="tabs-cell"> <div>菜單一</div> <ul> <li class="tabs-cell tabs-cell-2"> <div>菜單一一</div> <ul > <li>1-1-1</li> <li>1-1-2</li> <li>1-1-3</li> <li>1-1-4</li> <li>1-1-4</li> </ul> </li> <li class="tabs-cell tabs-cell-2"> <div>菜單一二</div> <ul> <li>1-2-1</li> <li>1-2-2</li> <li>1-2-3</li> <li>1-2-4</li> </ul> </li> <li class="tabs-cell tabs-cell-2"> <div>菜單一三</div> <ul> <li>1-3-1</li> <li>1-3-2</li> <li>1-3-3</li> <li>1-3-4</li> </ul> </li> </ul> </div> <div class="tabs-cell"> <div>菜單二</div> <ul> <li class="tabs-cell tabs-cell-2"> <div>菜單二一</div> </li> <li class="tabs-cell tabs-cell-2"> <div>菜單二二</div> </li> <li class="tabs-cell tabs-cell-2"> <div>菜單二三</div> </li> </ul> </div> </div> <script> var cell=document.getElementsByClassName('tabs-cell') var tabs=document.getElementsByClassName('tabs')[0] for(var i=0;i<cell.length;i++){ cell[i].flag=true; cell[i].onclick=function(ev){ isShow(this) ev.stopPropagation() } } function isShow(obj){ var children=obj.parentNode.children for (var i = 0; i < children.length; i++) { /* var ul=children[i].getElementsByTagName('ul')[0]; ul.style.display='none'*/ var ul=children[i].getElementsByTagName('ul'); for (var k = 0; k < ul.length; k++) { ul[k].style.display='none' } if(children[i]!=obj){//改變this上下相鄰元素的開關狀態 children[i].flag=true; } } if(obj.flag){ obj.getElementsByTagName('ul')[0].style.display='block' }else{ obj.getElementsByTagName('ul')[0].style.display='none' } obj.flag=!obj.flag } // https://blog.csdn.net/wkj001/article/details/53840471 原生js如何獲取當前元素的同級元素 //實現原理:獲取當前元素以後,而後在獲取它的父元素,再獲取父元素的全部子元素,最後遍歷判斷每個子元素是否是當前元素,不是就將它的字體顏色設置爲紅色,就這麼簡單。 </script> </body> </html>