<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>tab选项卡</title> </head> <style> ul,li{margin: 0; padding:0; list-style: none;} a{text-decoration: none; color: cornflowerblue;} a:hover{text-decoration: #0000ff underline;} .tab-container{width: 360px; height: 165px;} .tab-nav{overflow: hidden;} .tab-nav ul li{float: left; width: 120px; height: 35px; line-height: 35px; text-align: center; cursor: pointer;} .active{background-color: lightblue;} .tab-content .detail{line-height: 35px; min-height: 120px; padding: 10px 0 0 20px; display: none;} .detail.active{display: block;} </style> <body> <p></p> <div> <!-- 选项卡的标签导航 --> <div> <ul> <li data-index="1">手机</li> <li data-index="2">衣服</li> <li data-index="3">鞋</li> </ul> </div> <!-- 标签导航对应的内容区 --> <div> <div class="detail active" data-index="1"> <ul> <li><a href="">华为mate20</a></li> <li><a href="">荣耀v20</a></li> <li><a href="">华为p30</a></li> </ul> </div> <div data-index="2"> <ul> <li><a href="">T恤</a></li> <li><a href="">***裤</a></li> <li><a href="">格子衫</a></li> </ul> </div> <div data-index="3"> <ul> <li><a href="">阿迪</a></li> <li><a href="">耐克</a></li> <li><a href="">NB</a></li> </ul> </div> </div> </div> <script> // 获取标签页导航tab,以及可点击的所有标签页<li>,并转为数据对象 var tabNav = document.getElementsByClassName('tab-nav').item(0); var tabList = tabNav.firstElementChild.children; var tabArr = Array.prototype.slice.call(tabList,0); // 获取所有详情页,并转为数据对象 var detail = document.getElementsByClassName('detail'); var detailArr = Array.prototype.slice.call(detail,0); // 利用冒泡,进行事件委托 tabNav.addEventListener('click',showDetail,false); // 监听tab点击事件 function showDetail(ev) { // 1.清空原导航标签的样式,并设置当前正在被点击的标签页为当前页 tabArr.forEach(function (tab) { tab.classList.remove('active') }); ev.target.classList.add('active'); // 清空所在详情页样式,并根据与导航data-index属性的对象关系,显示对应的详情页面 detailArr.forEach(function (detail) { detail.classList.remove('active') }); detailArr.forEach(function (detail) { // 详情页的index与导航标签的index相同时,显示该页面 if(detail.dataset.index ===ev.target.dataset.index){ detail.classList.add('active'); } }) } tabNav.addEventListener('mouseover',showDetail,false); </script> </body> </html>