1、面向对象的选项卡在直接书写上比较困难,咱们可以先用面向过程的方式写一个选项卡,然后按照:将变量变为属性,将函数变为方法的方式,通过构造函数替换window.onload进而初始化程序。
2.首先应该将其函数嵌套进行替换,使其不包含函数嵌套成分,然后看清楚this指向的值在对个别进行调整。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>面向对象的选项卡</title>
<style>
#div1 input{
width: 60px;
background: #1EE6E0;
}
#div1 input.active{
background: #15F443;
}
#div1 div{
width: 200px;
height: 150px;
background:#CCC;
display: none;
}
</style>
<script>
window.onload=function()
{
new TabSwitch('div1');
};
function TabSwitch(id)
{
var that=this;
var oDiv = document.getElementById(id);
this.aBtn = oDiv.getElementsByTagName('input');
this.aDiv = oDiv.getElementsByTagName('div');
for (var i = 0; i < this.aBtn.length; i++)
{
this.aBtn[i].index=i;
this.aBtn[i].onmouseover=function()
//与下面的that并不是同一个,所以下面的this要用that替换
{
that.fnMouse(this); //防止赋值给onmouseover事件,要写成函数模式
};
}
};
//oBtn可以是任意值,只要与下文对应即可
TabSwitch.prototype.fnMouse=function(oBtn)
{
for (var i = 0; i < this.aBtn.length; i++)
{
this.aBtn[i].className='';
this.aDiv[i].style.display = 'none';
}
oBtn.className='active';
this.aDiv[oBtn.index].style.display='block';
};
</script>
</head>
<body>
<div id="div1">
<input type="button" value="1" class="active">
<input type="button" value="2">
<input type="button" value="3">
<div style="display: block;">111</div>
<div>222</div>
<div>333</div>
</div>
</body>
</html>