本文實例講述了JS基於面向對象實現的選項卡效果。分享給大家供大家參考,具體如下:
中間過渡環節:把面向過程的程序,改寫成面向對象的形式
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 input {background:#CCC;}
#div1 .active {background:yellow;}
#div1 div {width:200px; height:200px; background:#CCC; display:none;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script>
window.onload=function ()
{
var oDiv=document.getElementById('div1');
var aBtn=oDiv.getElementsByTagName('input');
var aDiv=oDiv.getElementsByTagName('div');
var i=0;
for(i=0;i<aBtn.length;i++)
{
aBtn[i].index=i;
aBtn[i].onclick=function ()
{
for(i=0;i<aBtn.length;i++)
{
aBtn[i].className='';
aDiv[i].style.display='none';
}
this.className='active';
aDiv[this.index].style.display='block';
};
}
};
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="教育" />
<input type="button" value="財經" />
<input type="button" value="aaa" />
<div style="display:block;">1asdfasdfds</div>
<div>2xzcvxzcv</div>
<div>5332342345</div>
</div>
</body>
</html>
改寫注意事項:
1.前提:所有代碼必須包含在window.onload裡面
2.去掉函數嵌套(window.onload裡面嵌套的函數拎到window.onload外面去)
3.不能有函數嵌套,但可以有全局變量(比如onclick函數拎出去後,aBtn是window.onload函數裡的私有變量,onclick函數不能用)
過程:
1.onload(初始化整個程序)→構造函數(初始化一個對象)
2.全局變量→屬性
3.函數→方法
window.onload=function(){
var oTab=new TabSwitch("div1");
}
function TabSwitch(id)
{
var oDiv=document.getElementById(id);
this.aBtn=oDiv.getElementsByTagName('input');
this.aDiv=oDiv.getElementsByTagName('div');
var i=0;
var _this=this; //this是new出來的對象,即oTab
for(i=0;i<this.aBtn.length;i++)
{
this.aBtn[i].index=i;
this.aBtn[i].onclick=function(){
_this.tab(this); //通過參數的形式,將被點擊的按鈕傳到下面去
};
}
};
TabSwitch.prototype.tab=function(oBtn){
for(i=0;i<this.aBtn.length;i++)
{
this.aBtn[i].className='';
this.aDiv[i].style.display='none';
}
oBtn.className='active'; //要被點擊的按鈕改變,而不是new出來的對象,所以這裡不用this
this.aDiv[oBtn.index].style.display='block';
}
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript切換特效與技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript查找算法技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript中json操作技巧總結》、《JavaScript錯誤與調試技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。