鉴于UI妹妹每次交付过来的选项卡都夹带了多多少少的js,而且每遇到选项卡就加一点js,造成垃圾低劣代码逐渐堆积过多了,一直想做一个通用简洁的选项卡库。
第一步:引用table.js 
复制代码 代码如下:
<script type="text/javascript" src="https://www.jb51.net/table.js"> </script>
第二步:定义选中的样式,比如“active”,应用选项卡的块的ID,比如“sidebar”,默认被选中的序号,比如第一个“0”;
第三步:调用函数:
复制代码 代码如下:
<script type="text/javascript"> 
//参数分别为:默认选择项 应用块的id 选中的样式 
table(0, "sidebar", "active") 
</script> 
一切OK,选项卡响应click事件,兼任IE和FF,等有时间了再优化,效果如下:

HTML源代码如下:
复制代码 代码如下:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>New Web Project</title> 
<script type="text/javascript" src="https://www.jb51.net/table.js"> </script> 
<style type="text/css"> 
.sidebar { 
width: 140px; 
background: #C9E4D6; 
min-height: 600px; 
float: left; 
border-left: solid 1px #C8C8C8; 
} 
.sidebar ul { 
list-style:none; 
text-align: left; 
padding: 20px 0px 0px 0px; 
} 
.sidebar ul li { 
border-bottom: 1px dotted #C8C8C8; 
font-size: 14px; 
height: 30px; 
line-height: 30px; 
padding-left: 15px; 
margin-left: 15px; 
cursor: pointer; 
} 
.sidebar .active { 
background: #fff; 
} 
</style> 
</head> 
<body> 
<div> 
<ul> 
<li> 
选项一 
</li> 
<li> 
选项二 
</li> 
<li> 
选项三 
</li> 
<li> 
选项四 
</li> 
<li> 
选项五 
</li> 
</ul> 
</div> 
</body> 
<script type="text/javascript"> 
//参数分别为:默认选择项 应用块的id 选中的样式 
table(0, "sidebar", "active") 
</script> 
</html> 
table.js
复制代码 代码如下:
 
/** 
* @author Sky 
*/ 
var table=function(index,id,active) 
{ 
table=new Table(index,id,active); 
table.bind(); 
} 
var Table=function(index,id,active) 
{ 
this.index=parseInt(index); 
this.arr=document.getElementById(id).getElementsByTagName("li"); 
this.active=active; 
} 
Table.prototype={ 
bind:function() 
{ 
this.arr[this.index].className=this.active;//初始化 
var _self=this; 
for (var i = 0; i < this.arr.length; i++) 
{ 
this.arr[i].setAttribute("ext", i); 
this.arr[i].onclick = function(e) 
{ 
var _e = window.event||e; 
var _target=_e.srcElement || _e.target; 
_self.setClass(parseInt(_target.getAttribute("ext"))); 
} 
} 
}, 
setClass:function(index) 
{ 
this.arr[this.index].className=""; 
this.arr[index].className=this.active; 
this.index=index; 
} 
} 
DEMO下载
您可能感兴趣的文章:
