效果图:
HTML部分
<div class="tab"><div class="tab_top"><ul><li class="current">水果</li><li>家电</li><li>书籍</li><li>服装</li></ul></div><div class="tab_bottom"><div class="item" style="display: block;">水果区域</div><div class="item">家电区域</div><div class="item">书籍区域</div><div class="item">服装区域</div></div></div>
css部分
*{margin: 0;padding: 0;}.tab{margin: 100px auto;width: 500px;height: 600px;/* border: 1px solid red; */}.tab_top{width: 100%;height: 30px;background-color: #ccc;border-bottom: 3px solid red;}li{list-style: none;float: left;width: 80px;height: 30px;line-height: 30px;margin: 0 auto;text-align: center;/* background-color: red; */}.tab_bottom{margin-top: 30px;}.current{color: #fff;background-color: red;}li:hover{color: darkred;}.item{display: none;}
js代码部分
<script>var tabTop = document.querySelector('.tab_top')var lis = document.querySelectorAll('li')var items = document.querySelectorAll('.item')for (var i = 0; i < lis.length; i++){lis[i].setAttribute('index',i)lis[i].onclick = function () {for (var i = 0; i < lis.length; i++) {lis[i].className = ''}this.className = 'current'var index = this.getAttribute('index')for (var i = 0; i < items.length; i++){items[i].style.display = 'none'}items[index].style.display = 'block'}}</script>