<!DOCTYPE html> <html> <head> <title>js基础学习-tab切换作业</title> <style type="text/css"> h2 { border-top: solid #ccc 1px; border-left: solid #ccc 1px; width: 50px; height: 25px; margin: 0; float: left; text-align: center; } .tab-content { border: solid cornflowerblue 1px; width: 152px; height: 100px; } /*全部内容隐藏*/ .tab-content div{ display: none; text-align: center; } /*显示此div的内容*/ .tab-content .show{ display: block; } .like { background-color: #ccc; } </style> </head> <body> <div class="tab-head"> <h2 onmouseover="changeTab(0)" class="like">1</h2> <h2 onmouseover="changeTab(1)">2</h2> <h2 onmouseover="changeTab(2)">3</h2> </div> <div class="tab-content"> <div class="show">朱老师</div> <div>灭绝老师</div> <div>欧阳老师</div> </div> <script type="text/javascript"> var tabs = document.getElementsByClassName('tab-head')[0].getElementsByTagName('h2'), contents = document.getElementsByClassName('tab-content')[0].getElementsByTagName('div'); function changeTab(index) { for(var i = 0, len = tabs.length; i < len; i++) { if(i === index) { /*改变这个索引里面的属性*/ tabs[i].className = 'like'; // 更改属性为展示; contents[i].className = 'show'; }else{ tabs[i].className = ''; contents[i].className = ''; } } } // className:将某个元素的属性给当前的这个元素,通过class的名来赋予; </script> </body> </html>
总结: