js动态选项卡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul,
li {
list-style: none;
}
.box {
width: 400px;
height: 300px;
margin: 30px auto;
background-color: blueviolet;
}
.nav {
width: 400px;
height: 80px;
display: flex;
}
.nav li {
border: 1px solid black;
flex: 1;
font-size: 50px;
text-align: center;
line-height: 80px;
}
.nav>li {
background-color: blue;
}
.nav .active {
background-color: chartreuse;
color: white;
}
/* 添加图片 */
.box .imgbox {
width: 398px;
height: 220px;
position: relative;
}
.box .imgbox img {
width: 100%;
height: 100%;
position: absolute;
}
</style>
</head>
<body>
<div class="box">
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div class="imgbox">
<img src="./images/1.jpeg" alt="">
<img src="./images/2.jpeg" alt="">
<img src="./images/4.jpg" alt="">
<img src="./images/3.jpg" alt="">
</div>
</div>
</body>
</html>
<script>
var anav = document.querySelectorAll(".nav li");
var aimg = document.querySelectorAll("img");
// 先获取每个按钮
for (var i = 0; i < anav.length; i++) {
anav[i].index = i;//保存按钮的索引
anav[i].onclick = function () {
for (var j = 0; j < aimg.length; j++) {
aimg[j].style.display = "none";//先让所有的图片隐藏
}
for (var i = 0; i < anav.length; i++) {//清空按钮的类名,否则每次点击时都是active的样式
anav[i].className = "";
}
this.className = "active";//点击按钮时按钮的颜色为active的样式
aimg[this.index].style.display = "block"; //点击按钮,显示同索引的图片
}
}
</script>