html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/tab.css">
</head>
<body>
<div id="Tab" class="Tab">
<div class="tab_title">
<div>tab1</div>
<div>tab2</div>
<div>tab3</div>
</div>
<div class="tab_panel">
<div class="panel"> panel_1</div>
<div class="panel"> panel_2</div>
<div class="panel"> panel_3</div>
</div>
</div>
<div id="Tab2" class="Tab">
<div class="tab_title">
<div>tab1</div>
<div>tab2</div>
<div>tab3</div>
</div>
<div class="tab_panel">
<div class="panel"> panel_1</div>
<div class="panel"> panel_2</div>
<div class="panel"> panel_3</div>
</div>
</div>
<script src="js/tab.js"></script>
<script>
new Tab("#Tab",1);//1
new Tab("#Tab2");
</script>
</body>
</html>
css
*{
padding: 0;
margin: 0;
}
.Tab{
width: 250px;
height: 140px;
border:solid 0px #ccc;
margin-left: 50px;
margin-top: 50px;
}
.tab_title{
width: 100%;
height: 35px;
border:solid 0px red;
display: flex;
}
.tab_title div{
width:50px;
height:inherit;
text-align: center;
border: solid 1px transparent;
line-height: 35px;
color: black;
margin-top: auto;
}
.tab_title div:hover{
color: #75f2ff;
cursor: pointer;
}
.tab_title div.active{
border-color: #ccc #ccc white #ccc;
background-color: white;
color:#ff6d1f;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.tab_panel div.active{
display: block;
}
.tab_panel{
width: 100%;
height: 115px;
border: solid 1px #ccc;
}
.tab_panel div{
width: 100%;
height: inherit;
padding: 10px;
display: none;
}
js
//这里的参数tab是可以自己选择的 诺不选择则为默认值
function Tab(tabId,active,tab){
this.init(tabId,active,tab);//2
}
Tab.prototype.init =function(tabId,active,tab){
tab = tab || {};
this.titles = tab.titles || ".tab_title div";
this.tabs = tab.tabs || ".tab_panel div";
active = active || 0;//若用户没有传入值则默认显示下标为0的 否则显示用户自己选择的
var elem = document.querySelector(tabId);
console.log(elem);
this.tabTitle = elem.querySelectorAll(this.titles);
this.tabPanel = elem.querySelectorAll(this.tabs);
this.active(active);//3
this.event();
};
Tab.prototype.active= function(index){
if(index===this.current){
return ;
}
//4
this.tabTitle[index].classList.add("active");
this.tabPanel[index].classList.add("active");
console.log(this.current)
if(typeof this.current === "number"){//5
//当current等于整型的时候 当前index是不会和current相等的
//也就是说当current等于1时 index等于0 所以这样就实现了一个选项卡的效果 等于1的隐藏 等于0的显示
this.tabTitle[this.current].classList.remove("active");
this.tabPanel[this.current].classList.remove("active");
}
this.current = index;//6
};
Tab.prototype.event= function(){
var len = this.tabTitle.length;
var that = this;
for(let i=0;i<len;i++){
this.tabTitle[i].addEventListener("click",function(){
that.active.call(that,i);//7
})
}
};