由于程序需求,自定义了一个简单的Web Tab控件,能够实现Tab的功能,但存在如下几个不足:
1)响应事件showTab不够通用,没有把tabs作为参数传入;
2)当Tab超过一行时,会折行,而不会隐藏或者左右滑动;
3)Tab样式较简陋,没有太多修饰。
代码如下,仅供参考:
<html>
<head>
<title>Tab控件示例</title>
<script type="text/javascript" language="javascript">
var tabs = [{name: '古典文学', value: 0, selected: true, contentPanel: 'classicalPanel', initComp: function(){alert("0");}},
{name: '侦探小说', value: 1, selected: false, contentPanel: 'detectPanel', initComp: function(){alert("1");}},
{name: '科谱读物', value: 2, selected: false, contentPanel: 'sciencePanel', initComp: function(){alert("2");}}];
var tabsDef = {tabNamePrefix: 'x_tab_label_', tabs: tabs};
//创建Tabs控件(divId为填充的Div,tabsDef为各标签页定义数组)
function createTabs(divId, tdef){
var divObj = document.getElementById(divId);
if(divObj == null || tdef == null) return;
var divHTML = ""; var selectValue = "";
for(var i = 0;i < tdef.tabs.length;i++){
var bname = tdef.tabNamePrefix + tdef.tabs[i].value;
divHTML += "<label style='background: #D0D0D0' id='" + bname + "' οnclick='showTab(\"" + tdef.tabs[i].value + "\");'>" + tdef.tabs[i].name + "</label> ";
if(tdef.tabs[i].selected == true) selectValue = "" + tdef.tabs[i].value;
}
divHTML += "<br/>";
//alert(divHTML);
divObj.innerHTML = divHTML;
displayComponent(divId, true);
if(selectValue != "") showTab(selectValue);
}
//显示某一标签
function showTab(iTab){
var tabIndex = -1;
iTab = "" + iTab;
for(var i = 0;i < tabs.length;i++){
var tname = tabsDef.tabNamePrefix + tabs[i].value;
var bobj = document.getElementById(tname);
var v = "" + tabs[i].value;
if(v == iTab){
tabIndex = i;
if(bobj != null){
bobj.style.background = "#A0A0A0";
bobj.style.border = "solid thin black";
}
}else{
displayComponent(tabs[i].contentPanel, false);
if(bobj != null){
bobj.style.background = "#D0D0D0";
bobj.style.border = "none";
}
}
}
if(tabIndex >= 0){
displayComponent(tabs[tabIndex].contentPanel, true);
if(tabs[tabIndex].initComp != null) tabs[tabIndex].initComp();
}
}
//显示或隐藏某一组件
function displayComponent(compId, isVisible){
var comp = document.getElementById(compId);
if(comp == null) return;
comp.style.display = isVisible ? "" : "none";
}
</script>
</head>
<body>
<div id="tabFrame" style="display: none">
</div>
<div id="classicalPanel" style="border:outset thin; width: 100%;">古典文学Tab内容。。。</div>
<div id="detectPanel" style="border:outset thin; width: 100%;">侦探小说Tab内容。。。</div>
<div id="sciencePanel" style="border:outset thin; width: 100%;">科普读物Tab内容。。。</div>
<script type="text/javascript" language="javascript">
createTabs("tabFrame", tabsDef);
</script>
</body>
</html>