点击选项卡的示例
使用面向对象实现一个简单的点击选项卡的示例
css代码部分
* {
padding: 0;
margin: 0;
}
ul,
li {
list-style: none;
}
.container {
width: 600px;
margin: 100px auto;
}
.container ul {
width: 100%;
height: 50px;
background-color: pink;
display: flex;
}
.container ul li {
width: 200px;
height: 100%;
text-align: center;
line-height: 50px;
border: 1px solid darkblue;
}
.container ul .active {
background-color: skyblue;
}
.container ol {
position: relative;
width: 100%;
height: 300px;
background-color: rgb(187, 187, 168);
text-align: center;
line-height: 300px;
font-size: 20px;
}
.container ol li {
position: absolute;
left: 50%;
transform: translateX(-50%);
display: none;
}
.container ol .on {
display: block;
}
js代码部分
function Tab(id){
this.root = document.querySelector(id)
this.uls = this.root.querySelectorAll('ul>li')
this.ols = this.root.querySelectorAll('ol>li')
let that = this
this.onTab =function(){
for(let i = 0 ; i < this.uls.length; i++){
this.uls[i].onclick = function(){
that.clear()
this.classList.add('active')
let index = this.getAttribute('data-index')
that.ols[i].classList.add('on')
}
}
}
this.clear = function(){
for(let i = 0;i < this.uls.length;i++){
this.uls[i].classList.remove('active')
this.ols[i].classList.remove('on')
}
}
}
let table =new Tab('#tab1')
table.onTab()
html结构部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container" id="tab1">
<ul>
<li class="active" data-index="0">选项1</li>
<li data-index="1">选项2</li>
<li data-index="2">选项3</li>
</ul>
<ol>
<li class="on">区块1</li>
<li>区块2</li>
<li>区块3</li>
</ol>
</div>
</body>
</html>
|