<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{padding: 100px;}
#box ,#box2{
position: relative;
margin-top: 30px;
width: 550px;
height: 550px;
}
.active{background: #f00;}
#box div,#box2 div{
border: 1px solid #ccc;
width: 500px;
height: 500px;
position: absolute;
top: 35px;
left: 0;
display: none;
}
</style>
</head>
<body>
<div id="box">
<input class="active" type="button" name="" id="" value="a" />
<input type="button" name="" id="" value="b" />
<input type="button" name="" id="" value="c" />
<input type="button" name="" id="" value="d" />
<div style="display: block;">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div id="box2">
<input class="active" type="button" name="" id="" value="a" />
<input type="button" name="" id="" value="b" />
<input type="button" name="" id="" value="c" />
<input type="button" name="" id="" value="d" />
<div style="display: block;">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</body>
<!--面向过程-->
<!--<script type="text/javascript">
var oBox = document.getElementById('box');
var aBtn = oBox.getElementsByTagName('input');
var aDiv = oBox.getElementsByTagName('div');
for(var i=0;i<aBtn.length;i++){
aBtn[i].index = i;
aBtn[i].onclick = fnSwitch;
}
function fnSwitch(){
for(var i=0;i<aBtn.length;i++){
aBtn[i].className = "";
aDiv[i].style.display = "none";
}
aBtn[this.index].className = "active";
aDiv[this.index].style.display = "block";
}
</script>-->
<!--面向过程改成面向对象的方法
1、onload里面创建实例使用方法
2、全局变量就是属性
3、函数就是方法
4、改变this指针,this指向object-->
<!--面向对象-->
<script type="text/javascript">
// 调用 如果不写window.onload这个函数,调用要写到最后面
window.onload = function(){
var t1 = new Tab('box');
t1.ints();
t1.auto();
var t2 = new Tab('box2');
t2.ints();
t2.auto();
}
// 构造函数,设置属性
function Tab(id){
this.oBox = document.getElementById(id); //传参数
this.aBtn = this.oBox.getElementsByTagName('input');
this.aDiv = this.oBox.getElementsByTagName('div');
this.now = 0;
}
// 原型,设置方法
Tab.prototype.ints = function(){
var _this = this;
for(var i=0;i<this.aBtn.length;i++){
this.aBtn[i].index = i;
this.aBtn[i].onclick = function(){
_this.fnSwitch(this); //this改变指针,传参
} ;
}
}
//选项卡事件
Tab.prototype.fnSwitch = 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";
}
//自动轮播选项卡
Tab.prototype.auto = function(){
var _this = this;
setInterval(function(){
_this.now++;
if(_this.now == _this.aBtn.length){
_this.now = 0;
}
for(var i=0;i<_this.aBtn.length;i++){
_this.aBtn[i].className = "";
_this.aDiv[i].style.display = "none";
}
_this.aBtn[_this.now].className = "active";
_this.aDiv[_this.now].style.display = "block";
},3000)
}
</script>
</html>
js面向对象---选项卡
最新推荐文章于 2022-07-20 13:03:00 发布