html代码
<body>
<div id="div1">
<input class="active" type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<div style="display: block;">1111</div>
<div>2222</div>
<div>3333</div>
</div>
<div id="div2">
<input class="active" type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<div style="display: block;">1111</div>
<div>2222</div>
<div>3333</div>
</div>
</body>
css代码
<style>
#div1 div ,#div2 div{
width: 200px;
height: 200px;
border: 1px solid red;
display: none;
}
.active{
background: red;
}
</style>
js代码
要注意 点击事件 定时器 等 函数中this的指向
<script>
var div1 = null;
var aIpt = null;
var aDiv = null;
window.onload = function () {
var t1 = new Tab("div1");
t1.init();
var t2 = new Tab("div2");
t2.aotoPlay(2000);
};
function Tab(id) {
this.div1 = document.getElementById(id);
this.aIpt = this.div1.getElementsByTagName("input");
this.aDiv = this.div1.getElementsByTagName("div");
this.iNow = 0; //自动轮播用
}
Tab.prototype.init = function() {
//this ==> t1
var This = this;
for(var i = 0;i < this.aIpt.length;i++){
this.aIpt[i].index = i;
this.aIpt[i].onclick = function () {
This.change(this);
};
}
};
Tab.prototype.change = function(obj){
for(var j = 0;j < this.aDiv.length;j++){
this.aDiv[j].style.display = "none";
this.aDiv[obj.index].style.display = "block";
this.aIpt[j].className = "";
obj.className = "active"
}
};
//自动轮播
Tab.prototype.aotoPlay = function (time) {
var This = this;
setInterval(function () {
This.iNow++;
if(This.iNow >=This.aDiv.length){
This.iNow = 0;
}
for(var j = 0;j < This.aDiv.length;j++){
This.aDiv[j].style.display = "none";
This.aDiv[This.iNow].style.display = "block";
This.aIpt[j].className = "";
This.aIpt[This.iNow].className = "active"
}
},time)
}
</script>