<style> * { margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; height: 100vh; } .box-tab { width: 620px; height: 600px; } .box-tab .tab_list { background: rgb(238, 241, 238); border: 1px solid rgb(203, 206, 203); width: 600px; height: 40px; } .box-tab .tab_list ul { list-style: none; } .box-tab .tab_list ul li { float: left; width: 120px; height: 40px; text-align: center; line-height: 40px; cursor: pointer; } .alone { background-color: red; color: aliceblue; } .box-tab .tab_cont { width: 600px; height: 300px; border-bottom: 1px solid rgb(203, 206, 203); border-left: 1px solid rgb(203, 206, 203); border-right: 1px solid rgb(203, 206, 203); } .box-tab .tab_cont .tab_item { display: none; padding-left: 30px; padding-top: 20px; } </style> </head> <div class="box-tab"> <div class="tab_list"> <ul> <li class="alone">商品介绍</li> <li>规格与包装</li> <li>售后保障</li> <li>商品评价</li> <li>手机社区</li> </ul> </div> <div class="tab_cont"> <div class="tab_item" style="display: block;">这是件好商品</div> <div class="tab_item">这是个包装</div> <div class="tab_item">售后挺好</div> <div class="tab_item">五星好评</div> <div class="tab_item">手机针不戳</div> </div> </div> </body> <script> // 获取tab栏 var lis = document.querySelector('.tab_list').querySelectorAll('li'); var items = document.querySelector('.tab_cont').querySelectorAll('.tab_item'); // 遍历所有tab栏,给所有li标签添加点击事件 for (var i = 0; i < lis.length; i++) { lis[i].setAttribute('index', i); lis[i].onclick = function() { // 使用排它思想把所有li标签样式全部取消只保留当前点击的li标签 for (var i = 0; i < lis.length; i++) { lis[i].className = ''; } this.className = 'alone'; var index = this.getAttribute('index'); for (var i = 0; i < items.length; i++) { items[i].style.display = 'none'; } items[index].style.display = 'block'; } } </script>