本文介绍一种基于 JavaScript 的通用选项卡实现方法,代码简洁且兼容 IE 和 Firefox。通过传入默认选中项、容器 ID 及激活样式名,即可快速实现点击切换效果。文章包含完整的 HTML 结构、CSS 样式及核心 JS 逻辑,适合需要轻量级交互方案的项目。
引入 JavaScript 文件
参考以下代码示例:
<script type="text/javascript" src="table.js"> </script> 第二步:设置选中状态的样式
其中,参数分别代表:默认选中的索引值(例如第一个选项为 0)、应用选项卡功能的容器 ID(例如 "sidebar"),以及用于标识选中状态的 CSS 类名(例如 "active")。
第三步:执行调用函数:
调用选项卡函数
具体调用代码如下:
<script type="text/javascript">
// 参数说明:默认选中项索引、应用块的 ID、选中的样式类名
table(0, "sidebar", "active")
</script> 配置完成后,选项卡即可响应 click 事件,并兼容 IE 和 Firefox 浏览器。后续如有时间可进一步优化,当前效果如下图所示:

HTML源代码如下:
HTML 结构示例
完整的 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="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 class="sidebar" id="sidebar">
<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
核心 JS 代码实现
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 下载