原生js完成tab切换
- 思路
- 给点击切换的内容绑定对应的下标
- 根据下标完成对应模块的显示隐藏
- 排他法
效果图:
源代码:
<!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>tab切换</title>
<style>
* {
margin: 0;
padding: 0;
}
box {
width: 100%;
}
.top {
height: 50px;
line-height: 50px;
display: flex;
margin-bottom: 10px;
text-align: center;
}
a {
text-decoration: none;
flex: 1;
color: rgb(61, 61, 61);
}
.top>a:nth-of-type(1) {
background-color: #428ac2;
}
.top>a:nth-of-type(2) {
background-color: orange;
}
.color:nth-of-type(1) {
width: 100%;
height: 300px;
background-color: #428ac2;
text-align: center;
line-height: 300px;
}
.color:nth-of-type(2) {
width: 100%;
height: 300px;
background-color: orange;
display: none;
text-align: center;
line-height: 300px;
}
.active {
font-size: 20px;
font-weight: 900;
color: white;
/* color: #df6921; */
/* color: #33986f; */
}
</style>
</head>
<body>
<div class="box">
<div class="top">
<a href="#" class="active">我是天蓝色部分</a>
<a href="#">我是橘黄色部分</a>
</div>
<div class="box2">
<div class="color">天蓝色</div>
<div class="color">橘黄色</div>
</div>
</div>
</body>
</html>
<script>
// 查找显示隐藏对应的div
var color = document.getElementsByClassName('color');
// 1.找到点击的a 给每一个a加一个下标
var a = document.getElementsByTagName('a');
console.log(a);
for (var i = 0; i < a.length; i++) {
// 此时 每一个a 标签 对应有一个下标 0 1
a[i].setAttribute('index', i);
// 当前a被点击时
a[i].onclick = function () {
//拿到被点击a的index 值 0 或者1
var index = this.getAttribute('index');
console.log(index);
// 使用排他法 选中的内容 添加一个active属性 未选中的去除class属性
for (var j = 0; j < a.length; j++) {
a[j].className = '';
a[index].className = 'active';
}
// 再次使用排他法 把对应a 对应的html进行显示隐藏
for (var k = 0; k < color.length; k++) {
color[k].style.display = 'none';
color[index].style.display = 'block';
}
}
}
</script>