js实现的垂直选项卡效果代码实例
本章节分享一段代码实例,它实现了简单的垂直选项卡效果。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.51texiao.cn/" /> <title>前端教程网</title> <style type="text/css"> *{ margin:0; padding:0; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; } .container{ margin:0 auto; width:500px; overflow:hidden; background:beige; } li{ border-top:1px solid lightgrey; border-left:1px solid lightgrey; border-right:1px solid lightgrey; height:35px; line-height:35px; list-style:none; text-align:center; width:100px; } li:last-child{ height:159px; border-right:1px solid lightgrey; border-bottom:1px solid lightgrey; } li.active{ border-right:1px solid white; background white; } li.normal{ border-right:1px solid white; background:red; } #tab_content{ float:right; width:400px; *width:394px; background: white; height: 300px; overflow: hidden; border-top: 1px solid lightgrey; border-right: 1px solid lightgrey; border-bottom: 1px solid lightgrey; border-left: 0px solid lightgrey; } #tab_content .content{ padding:15px; -moz-border-radius: 5px; height: 300px; } #tabnav a{text-decoration:none;} </style> </head> <body> <div class="container"> <div id="tab_content"> <div id="a" class="content">前端教程网一</div> <div id="b" class="content">前端教程网二</div> <div id="c" class="content">前端教程网三</div> <div id="d" class="content">前端教程网四</div> </div> <div > <ul id="tabnav"> <li ><a href="#a" >标题一</a></li> <li class="active"><a href="#b" >标题二</a></li> <li><a href="#c" >标题三</a></li> <li><a href="#d" >标题四</a></li> </ul> </div> </div> <script type="text/javascript"> function changeStyle(){ this.onclick=function(){ var list=this.parentNode.childNodes; for(var index=0;index<list.length;index++){ if(1==list[index].nodeType && 'active'==list[index].className){ list[index].className=""; } } this.className='active'; } } var tabs=document.getElementById('tabnav').childNodes; for(var index=0;index<tabs.length;index++){ if(1==tabs[index].nodeType){ changeStyle.call(tabs[index]); } } </script> </body> </html>
上面的代码实现了我们的要求,下面介绍一下它的实现过程。
一.代码注释:
(1).function changeStyle(){},此方法实现了注册事件处理函数的功能。
(2).this.onclick=function(){},注册事件处理函数,this在本代码中就是一个li元素。
(3).var list=this.parentNode.childNodes,获取当前li元素的父节点下所有的子节点。
(4).for(var index=0;index<list.length;index++){
if(1==list[index].nodeType && 'active'==list[index].className){
list[index].className="";
}
},遍历每一个节点。
如果当前节点类型是元素节点,也就是li元素,并且className属性值等于active
那么就将className属性值设置为空。
(5).this.className='active',将当前的className属性值设置为active。
(6).var tabs=document.getElementById('tabnav').childNodes,获取所有的标题li元素。
(7).for(var index=0;index<tabs.length;index++){
if(1==tabs[index].nodeType){
changeStyle.call(tabs[index]);
}
},遍历每一个子节点元素。
如果是元素节点,也就是li元素,那么就调用changeStyle()方法。
二.相关阅读:
(1).parentNode可以参阅js parentNode一章节。
(2).childNodes可以参阅js childNodes一章节。
(3).nodeType可以参阅js nodeType一章节。
(4).className可以参阅js className一章节。
(5).call()方法可以参阅js call()一章节。