面向对象小实例之 选项卡

直接上代码 :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#wrap1,
#wrap2,{
float: left;
}
div div{
border: 1px solid #000;
width: 200px;
height: 50px;
font-size: 20px;
text-align: center;
line-height: 50px;
display: none;
}
.active{
background: red;
}
</style>
</head>
<body>
</body>
<div id="wrap1">
<input type="button" value="aaa" class="active">
<input type="button" value="bbb">
<input type="button" value="ccc">
<div style="display: block;">aaa</div>
<div>bbb</div>
<div>ccc</div>
</div>
<div id="wrap2">
<input type="button" value="aaa" class="active">
<input type="button" value="bbb">
<input type="button" value="ccc">
<div style="display: block;">aaa</div>
<div>bbb</div>
<div>ccc</div>
</div>

<script type="text/javascript">

//原本面向过程的写法是酱紫的:
/*var btn=document.getElementsByTagName("input");
var div=document.getElementsByTagName("div");
for(var i=0;i<btn.length;i++){
btn[i].index=i;
btn[i].onclick=function(){
for(var i=0;i<btn.length;i++){
btn[i].className='';
div[i].style.display='none';
}
this.className='active';
div[this.index].style.display='block';
}

}*/

//后来,面向对象时酱紫的 :
function Tab(obj){
this.parentNode=document.getElementById(obj)
this.btn=this.parentNode.getElementsByTagName("input");
this.div=this.parentNode.getElementsByTagName("div");
this.init();
};
Tab.prototype.init=function(){
var _this=this;
for(var i=0;i<this.btn.length;i++){
this.btn[i].index=i;
this.btn[i].onclick=function(){
_this.clickFn(this);
};
}
};
Tab.prototype.clickFn = function(_this){
for(var i=0;i<this.btn.length;i++){
this.btn[i].className='';
this.div[i].style.display='none';
}
_this.className='active';
this.div[_this.index].style.display='block';
};
Tab.prototype.autoPlay = function(){
this.n=0;
var _this=this;
setInterval(function(){
_this.n++;
if(_this.n ==_this.btn.length){
_this.n=0;
}
for(var i=0;i<_this.btn.length;i++){
_this.btn[i].className='';
_this.div[i].style.display='none';
}
_this.btn[_this.n].className='active';
_this.div[_this.n].style.display='block';
},1000);


};
var t1=new Tab("wrap1");
var t2=new Tab("wrap2");
t1.autoPlay();
t2.autoPlay();
</script>
</html>

posted @ 2017-03-13 22:20  zhouyia~  阅读(110)  评论(0编辑  收藏  举报