<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <style type="text/css"> * { text-align: center; } .ul li { display: inline; width: 30%; text-decoration: none; padding: 18px; } .asd { background-color: blueviolet; } section { height: 300px; } </style> <div id="nav"> <ul class="ul"> <li class="asd">选项1</li> <li>选项2</li> <li>选项3</li> <li>选项4</li> </ul> </div> <div> <section class="tab" style="background-color: #7FFF00;"></section> <section class="tab" style="background-color: #ADD8E6;"></section> <section class="tab" style="background-color: antiquewhite;"></section> <section class="tab" style="background-color: aqua;"></section> </div> <script type="text/javascript"> var Nav = document.getElementsByTagName('li'); //引入HTML里的元素 console.log(Nav) var Div = document.getElementsByClassName('tab'); console.log(Div) for (var m = 1; m < Div.length; m++) { //使用for循环,全部隐藏 只显示第一个 Div[m].style.display = "none"; } for (let i = 0; i < Nav.length; i++) { //先全部循环一遍,加入点击事件 Nav[i].onclick = function() { console.log(i); for (var a = 0; a < Nav.length; a++) { //循环Nav标签,把Nav的className清空,Div标签隐藏 Nav[a].className = ''; Div[a].style.display = "none"; } Nav[i].className = 'asd'; //循环到这里,点击事件的显示 Div[i].style.display = "block"; } } </script> </body> </html>