由於程序需求,自定義了一個簡單的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 + "' onclick='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>