Javascript实现简单的Tabs
文章来源:365jz.com 点击数:
466 更新时间:2009-09-20 08:50
参与评论
css:
Code
#tabBox{border:#090 1px dashed; width:400px; height:200px;}
.span{margin:1px; line-height:30px; padding-left:15px; padding-right:15px;}
.span1{border:#999 1px solid; cursor:pointer;}
.span2{color:#9C0;
js:
Code
var $ = function(id){
return typeof(id)=="string"?document.getElementById(id):id;
}
//单个tab对象
function tab(titleDes,tabId){
this.titleDes = titleDes;
this.tabDom = $(tabId);
}
//tabs对象
function bravfTabs(containerId,titlesId){//containerId指整个tabs的容器的id(div类型),titlesId指所有tab标题的容器的id(div类型)
this.containerBox = $(containerId);//整个tabs的容器DOM
this.titlesBox = $(titlesId);//整个tab标题的容器DOM
this.tabs = new Array();//所有的tab
this.currentTabIndex = 0;//当前活动的tab索引
}
bravfTabs.prototype = {
init : function(){//初始化
this.createTitle();
this.initTabStyle();
this.regTitleClickEvent();
},
createTitle : function(){//根据tabs的titleDes生成对应tab的标题(span类型)
for(var i=0;i<this.tabs.length;i++){
var titleDom = document.createElement("span");
titleDom.id=i;
titleDom.className=(i==0)?"span span2":"span span1";
var titleContent = document.createTextNode(this.tabs[i].titleDes);
titleDom.appendChild(titleContent);
this.titlesBox.appendChild(titleDom);
}
},
initTabStyle : function(){//初始化所有tab的style
for(var i=0;i<this.tabs.length;i++){
var tabs = this.tabs;
i==0?
function(){tabs[i].tabDom.style.display="block";}()
:
function(){tabs[i].tabDom.style.display="none";}();
}
},
addTab : function(tab){//在tabs集合中添加tab
this.tabs[this.tabs.length]=tab;
},
regTitleClickEvent : function(){//注册tab标题(span)的点击事件
var titles = this.titlesBox.getElementsByTagName("span");
var self = this;
for(var i=0;i<titles.length;i++)
{
titles[i].onclick = function(){
titles[self.currentTabIndex].className="span span1";
self.tabs[self.currentTabIndex].tabDom.style.display="none";
self.currentTabIndex = parseInt(this.id);
titles[self.currentTabIndex].className="span span2";
self.tabs[self.currentTabIndex].tabDom.style.display="block";
}
}
}
}
window.onload = function(){
var demo = new bravfTabs("tabBox","tabControl");
demo.addTab(new tab("tab1","tab1"));
demo.addTab(new tab("tab2","tab2"));
demo.addTab(new tab("tab3","tab3"));
demo.addTab(new tab("tab4","tab4"));
demo.init();
html:
Code
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛
------分隔线----------------------------