代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin:0; padding:0; } ul, ul li{ list-style:none; } #box{ width:400px; height:300px; border:1px solid #000; margin:50px auto; } #list{ display:flex; border-bottom:1px solid #000; box-sizing:border-box; } #list li{ flex:1; text-align:center; border-right:1px solid #000; line-height:30px; box-sizing: border-box; cursor: pointer; } #list li:last-child{ border:none; } .item{ height:270px; display:none; } .active{ background:pink; color:#fff; } </style> </head> <body> <div id="box"> <!-- 选项卡按钮 --> <ul id="list"> <li class="active">食品</li> <li>服饰</li> <li>家电</li> <li>运动</li> </ul> <!-- 板块 --> <div class="item" style="display:block">食品板块</div> <div class="item">服饰板块</div> <div class="item">家电板块</div> <div class="item">运动板块</div> </div> <script> var lis = document.getElementsByTagName('li'); // 4 var items = document.getElementsByClassName('item'); // 4 for(var i=0;i<lis.length;i++){ // 给每个按钮添加索引 lis[i].index = i; lis[i].onclick = function(){ // 先把所有样式清空 先让所有板块隐藏 for(var j=0;j<lis.length;j++){ lis[j].className = ''; items[j].style.display = 'none'; } // 只给当前选中按钮添加样式 this.className ='active'; // 只给当前对应板块展示 items[this.index].style.display = 'block'; } } </script> </body> </html>
效果