JS 实现tab效果
一、效果描述:
点击标题显示对应内容
效果图:
二、代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>tab</title>
<!-- css样式 -->
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.box {
width: 300px;
height: 380px;
border: 1px solid #e2e2e2;
margin: 0 auto;
text-align: center;
}
.title {
width: 100%;
height: 60px;
display: flex;
}
.title li {
width: 25%;
line-height: 60px;
border: 1px solid #e2e2e2;
}
.title li.active{
background: #ff744a;
color: #fff;
}
.content {
position: relative;
}
.content li {
width: 100%;
height: 300px;
position: absolute;
left: 0;
top: 0;
display: none;
}
.content li.active{
z-index: 99;
display: block;
}
</style>
</head>
<body>
<!-- html部分的代码 -->
<div class="box">
<ul class="title">
<li class="active">标题1</li>
<li>标题2</li>
<li>标题3</li>
<li>标题4</li>
</ul>
<ul class="content">
<li class="active">内容1</li>
<li>内容2</li>
<li>内容3</li>
<li>内容4</li>
</ul>
</div>
</body>
<!-- js部分的代码 -->
<script>
var title = document.querySelectorAll(".title li");
var content = document.querySelectorAll(".content li");
var n = 0;
title.forEach(function (ele,index) {
ele.onclick = function () {
n = index;
//循环去掉所有标题的选中样式和对应内容的层级
for (let i = 0; i < title.length; i++) {
title[i].classList.remove("active");
content[i].classList.remove("active");
}
ele.classList.add("active");
content[n].classList.add("active");
}
})
</script>
</html>