<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin: 0;
list-style: none;
}
#box span, #box2 span{
width: 95px;
height: 40px;
background: darkgoldenrod;
float: left;
margin-right: 5px;
text-align: center;
line-height: 45px;
cursor: pointer;
}
#box p,#box2 p{
width: 295px;
height: 250px;
margin-top: 40px;
display: none;
border:1px solid firebrick;
}
.active {
color: white;
background:grey;
}
</style>
</head>
<body>
<div id="box">
<span class="active">选项卡1</span>
<span>选项卡2</span>
<span>选项卡3</span>
<p style="display: block;">内容1</p>
<p>内容2</p>
<p>内容3</p>
</div>
<div id="box2">
<span class="active">选项卡1</span>
<span>选项卡2</span>
<span>选项卡3</span>
<p style="display: block;">内容1</p>
<p>内容2</p>
<p>内容3</p>
</div>
<script type="text/javascript">
// var oBox = null;
// var oP = null;
var _this = this;
window.onload = function() {
new Tab(‘box’);new Tab(‘box2’);
};
function Tab(id) {
this.oBox = document.getElementById(id)
this.oP = this.oBox.getElementsByTagName('p');
// console.log(oP)
var _this = this;
this.oSpan = this.oBox.getElementsByTagName('span');
for (var i = 0; i < this.oSpan.length; i++) {
this.oSpan[i].index = i;
this.oSpan[i].onclick = function(){
_this.click(this);
};
};
};
// 将嵌套的函数抽取出来,作为方法
Tab.prototype.click = function(btn) { // 这里btn是个参数
for (var i = 0; i < this.oSpan.length; i++) {
this.oSpan[i].className = '';
this.oP[i].style.display = 'none';
};
//btn是要和span的当前的this保持一致
//this.className = 'active'; 这里的this是要改成属性this,但是改成this后就会和其他
//的this冲突,所以这里的this要传参数btn进来
btn.className = 'active';
this.oP[btn.index].style.display = 'block';
};
</script>
</body>