<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Tab切换</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 604px;
height: 400px;
box-shadow: 0px 2px 10px rgb(165, 165, 165);
margin: 0 auto;
}
.tit {
overflow: hidden;
}
.tit li {
float: left;
width: 150px;
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid #ccc;
border-top: none;
border-left: none;
list-style: none;
}
.con li {
height: 300px;
line-height: 300px;
text-align: center;
list-style: none;
display: none;
}
</style>
</head>
<body>
<div class="box">
<ul class="tit">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul class="con">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<script>
var lis = document.querySelectorAll(".tit li"); //获取tit下面的所有li 是一个html的集合
var cli = document.querySelectorAll(".con li"); //获取con下面的所有li 是一个html的集合
lis[0].style.backgroundColor = "red"; // 将tit下面的第一个(即索引为0)的li,背景颜色变为红色
cli[0].style.display = "block"; // 将con下面的第一个(即索引为0)的li,显示出来
cli[0].style.backgroundColor = "red"; 将con下面的第一个(即索引为0)的li,背景颜色变为红色
for (var i = 0; i < lis.length; i++) { //先con将lis里面的各个li循环出来 1
lis[i].index = i; //如何让下面的内容和上面的对应起来,那么我们可以全局获取一下这个索引 ★★★★★★ 5
lis[i].onclick = function () { //当我里面的其中一个li被点击时 2
for (var k = 0; k < lis.length; k++) {
lis[k].style.backgroundColor = ""; // 没有被点击的其他li背景色没有变化 4
cli[k].style.display = "none";
}
this.style.backgroundColor = "red"; //被我点击的这个li背景颜色变成红色 3
cli[this.index].style.display = "block"; // 当上面的li被点击时,我下面对应内容的索引同时跟着变化 this.index 6
cli[this.index].style.backgroundColor = "red"; // 7
}
}
</script>
</body>
</html>