<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.container{
width: 850px;
height: 200px;
background-color: #FF8500;
margin: 200px auto;
}
.top{
width: 850px;
height: 50px;
background-color: #9a6e3a;
}
.bottom{
width: 850px;
height: 150px;
background-color: #6F6D6D;
line-height: 150px;
text-align: center;
}
ul{
list-style: none;
width: 800px;
height: 50px;
float: left;
}
.top li{
width: 100px;
height: 50px;
float: left;
color: #FFFFFF;
line-height: 50px;
text-align: center;
font-size: 14px;
border-right: 1px solid #4182FA;
box-sizing: border-box;
position: relative;
}
p{
width: 50px;
height: 50px;
background-color:#FF8500;
float: right;
font-size: 20px;
text-align: center;
line-height: 50px;
color: #FFFFFF;
font-weight: 700;
}
.context li:nth-child(2){
display: none;
}
.context li:nth-child(3){
display: none;
}
.top li span{
position: absolute;
right: 0;
top: 0;
background-color:black;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
}
</style>
</head>
<body>
<div>
<div>
<ul>
<li>测试1<span>x</span></li>
<li>测试2<span>x</span></li>
<li>测试3<span>x</span></li>
</ul>
<p>+</p>
</div>
<div>
<ul>
<li>hello ~~测试1的内容</li>
<li>hello ~~测试2的内容</li>
<li>hello ~~测试3的内容</li>
</ul>
</div>
</div>
<script>
var that;
class Tab{
//实现tab栏的增查删改的功能
constructor(){
//获取元素
this.container = document.querySelector(".container");
this.lisTab = this.container.querySelector(".top").querySelectorAll("li"); //tab栏里面li
this.lisContext = this.container.querySelector(".context").querySelectorAll("li"); //内容里面的li
this.addBtn = this.container.querySelector("p");
this.topUl = this.container.querySelector(".top").querySelector("ul"); //获取top下的ul
that = this;
this.init()
}
//初始化方法给每个li添加绑定事件并设置自定义属性
init(){
for(var i = 0; i < this.lisTab.length; i++){
this.lisTab[i].setAttribute("data-index",i);
this.lisTab[i].onclick = this.toggle;
}
//给添加按钮绑定事件
this.addBtn.onclick = this.add;
}
//1.切换功能
toggle(){
for(var j = 0; j < that.lisTab.length;j++){
that.lisTab[j].style.backgroundColor = "#9a6e3a";
that.lisContext[j].style.display = "none"
}
this.style.backgroundColor = "#4182FA"; //设置当前的这个li的背景
//这里不能使用this.lisContext因为函数里面的this指向调用者这里的this指向被点击li
that.lisContext[this.getAttribute("data-index")].style.display = "block";
}
//2.添加tab栏
add(){
var li = document.createElement("li");
that.topUl.appendChild(li);
li.innerHTML = "测试" + that.lisTab.length
}
//3.删除
remove(){}
//4.修改
modify(){}
}
new Tab(); //实例化一个tab对象
</script>
</body>
</html>