<!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>
<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: 25px;
font-weight: 900;
color: rgb(207, 57, 57);
/* 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>
var cl = document.getElementsByClassName('color');
//获取a标签
var a = document.getElementsByTagName('a');
//利用for循环找到下标
for (var i = 0; i < a.length; i++) {
//for循环会主动运行无法正常获取下标,手动赋值来获取下标
a[i].setAttribute('index', i);
a[i].onclick = function () {
//获取index值,此时为0 1
var index = this.getAttribute('index');
//再利用for循环清除样式
for (var j = 0; j < a.length; j++) {
a[j].className = '';
a[index].className = 'active';
}
//利用for循环显示对应的内容
for (var k = 0; k < cl.length; k++) {
cl[k].style.display = 'none';
cl[index].style.display = 'block';
}
}
}
</script>
08-18
1900
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)