原生JS 选项卡代码实现
可实现同页面多个选项卡
效果图:
代码实现:
HTML部分
1 <div class="main" id="tabs"> 2 <div class="tabDiv"> 3 <a href="javascript:;" class="on">选项一</a> 4 <a href="javascript:;">选项二</a> 5 <a href="javascript:;">选项三</a> 6 </div> 7 <div class="con"> 8 1111111111111111111111111 9 </div> 10 <div class="con"> 11 2222222222222222222222222 12 </div> 13 <div class="con"> 14 3333333333333333333333333 15 </div> 16 </div> 17 18 <div class="main" id="tabs1"> 19 <div class="tabDiv"> 20 <a href="javascript:;" class="on">选项一</a> 21 <a href="javascript:;">选项二</a> 22 <a href="javascript:;">选项三</a> 23 </div> 24 <div class="con"> 25 1111111111111111111111111 26 </div> 27 <div class="con"> 28 2222222222222222222222222 29 </div> 30 <div class="con"> 31 3333333333333333333333333 32 </div> 33 </div>
JS部分
fnTab("tabs"); fnTab("tabs1"); function fnTab(id){ var parentEle = document.getElementById(id); var tabTools = getByClass(parentEle,"tabDiv")[0].getElementsByTagName("a"); var conArr = getByClass(parentEle,"con"); conArr[0].className += " active"; for(var i=0;i<tabTools.length;i++){ (function(i){ tabTools[i].onclick = function(){ for(var j=0;j<conArr.length;j++){ removeClass(tabTools[j],"on"); removeClass(conArr[j],"active"); } addClass(tabTools[i],"on"); addClass(conArr[i],"active"); } })(i); } } function getByClass(oParentEle,sClass){ if(oParentEle.getElementsByClassName){ var oEles = oParentEle.getElementsByClassName(sClass); return oEles; }else{ var oEles = oParentEle.getElementsByTagName("*"); var aRes = []; for(var i=0;i<oEles.length;i++){ if(oEles[i].className == sClass){ aRes.push(oEles[i]); } } return aRes; } } function addClass(ele,className){ if(ele && ele.nodeType == 1){ var reg = new RegExp("\\b"+className +"\\b","g"); if(!reg.test(ele.className)){ ele.className += " "+className; } } } function removeClass(ele,className){ if(ele && ele.nodeType == 1){ var reg = new RegExp("\\b"+className +"\\b","g"); if(reg.test(ele.className)){ ele.className = ele.className.replace(reg,""); } } }