注意:一个标签的class样式可以多次赋值同一值,不冲突,其实只有一个在其中,但remove一次后就没有了。
i.e. :
tag.children[1].classList.add('hide');
tag.children[1].classList.add('hide');
tag.children[1].classList.remove('hide');
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .item .header{ background-color: #2459a2; color: white; height: 35px; line-height:35px; } </style> </head> <body> <div style="height: 48px;"></div> <div style=" 300px;"> <div id="i1" class="item"> <div onclick="menu('i1')" class="header">菜单1</div> <div class="content hide"> <div>内容1</div> <div>内容2</div> <div>内容3</div> </div> </div> <div id="i2" class="item"> <div onclick="menu('i2')" class="header">菜单2</div> <div class="content hide"> <div>内容1</div> <div>内容2</div> <div>内容3</div> </div> </div> <div id="i3" class="item"> <div onclick="menu('i3')" class="header">菜单3</div> <div class="content hide"> <div>内容1</div> <div>内容2</div> <div>内容3</div> </div> </div> </div> <script type="application/javascript"> function menu(nid) { var tag = document.getElementById(nid); for (var i=0;i<tag.parentElement.children.length;i++) { tag.parentElement.children[i].children[1].classList.add('hide'); } tag.children[1].classList.remove('hide'); } </script> </body> </html>