下面进行一个简单的tab切换`
//css部分
<style>
.top {
width: 100%;
height: 50px;
line-height: 50px;
display: flex;
}
a {
text-decoration: none;
color: #666;
width: 50%;
text-align: center;
}
.a {
background-color: skyblue;
}
.b {
background-color: orange;
}
.active {
font-size: 20px;
font-weight: 600;
color: rgb(230, 62, 93);
}
main {
width: 100%;
height: 200px;
margin-top: 20px;
}
.box1 {
width: 100%;
height: 200px;
background-color: skyblue;
}
.box2 {
width: 100%;
height: 200px;
background-color: orange;
}
</style>
//html部分
<div class="top">
<a href="#" class="a active">我是天蓝色部分</a>
<a href="#" class="a b">我是橘黄色部分</a>
</div>
<main>
<div class="box box1"></div>
<div class="box box2" style="display: none;"></div>
</main>
//js部分
<script>
// 1.找到点击的a
var a = document.querySelectorAll('.a');
// 查找显示隐藏对应的box
var box = document.querySelectorAll('.box');
for (var i = 0; i < a.length; i++) {
//给每一个a加一个下标 此时 每一个a 标签 对应有一个下标 0 1
a[i].setAttribute('index', i);
// 当前a被点击时
a[i].onclick = function () {
//拿到被点击a的index 值 0 或者1
var index = this.getAttribute('index');
// 使用排他法 选中的内容 添加一个active属性 未选中的去除active属性
for (var j = 0; j < a.length; j++) {
a[j].classList.remove('active');
a[index].classList.add('active');
}
// 再次使用排他法 把对应的box进行显示隐藏
for (var k = 0; k < box.length; k++) {
box[k].style.display = 'none';
box[index].style.display = 'block';
}
}
}
</script>
展示的效果如图所示