html部分:
<nav class="app-tab"> <a href="item01" class="app-tab-item app-active">item01</a> <a href="item02" class="app-tab-item">item02</a> <a href="item03" class="app-tab-item">item03</a> </nav> <div class="app-content"> <div class="app-tab-content app-active" id="item01">我是选项卡1的内容</div> <div class="app-tab-content" id="item02">我是选项卡2的内容</div> <div class="app-tab-content" id="item03">我是选项卡3的内容</div> </div>
css部分:
<style type="text/css"> .app-tab-item { color: #F0F0F0; } .app-tab-item.app-active { color: red; } .app-tab-content { display: none; } .app-tab-content.app-active { display: block; } </style>
JavaScript部分:
// 事件委托 document.querySelector('.app-tab').addEventListener('click', function(event) { var target = event.target; if(target.tagName === 'A' && ~target.className.indexOf('app-tab-item')) { event.preventDefault(); event.stopPropagation(); // 避免重复点击 if(~target.className.indexOf('app-active')) { return; } // 选项卡切换 var activeTab = document.querySelector('.app-tab-item.app-active'); activeTab.className = activeTab.className.replace(' app-active', ''); target.className = target.className + ' ' + 'app-active'; // 内容区域切换 var href = target.getAttribute('href'); var activeContent = document.querySelector('.app-tab-content.app-active'); var targetContent = document.getElementById(href); activeContent.className = activeContent.className.replace(' app-active', ''); targetContent.className = targetContent.className + ' ' + 'app-active'; } }, false);