利用到了层叠,事件委托和自定义属性,唯一的缺点是num会一直自增,但是只要页面一刷新,num就重置了
下面放图
<!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>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
ul {
list-style: none;
}
.box {
width: 500px;
height: 300px;
margin: 100px auto;
}
.tab-header {
height: 40px;
line-height: 40px;
background-color: skyblue;
}
.tab-header ul {
display: flex;
}
.tab-header ul li {
width: 33.3333%;
cursor: pointer;
text-align: center;
}
.tab-body {
position: relative;
height: 260px;
}
.tab-body div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: pink;
}
.tab-body div:first-child {
z-index: 1;
}
.active {
color: red;
}
</style>
</head>
<body>
<div class="box">
<div class="tab-header">
<ul>
<li data-id="0" class="active">我的</li>
<li data-id="1">首页</li>
<li data-id="2">音乐</li>
</ul>
</div>
<div class="tab-body">
<div>个人中心内容</div>
<div>首页内容</div>
<div>音乐内容</div>
</div>
</div>
<script>
const ul = document.querySelector('.tab-header ul')
const contents = document.querySelectorAll('.tab-body div')
let num = 1
ul.addEventListener('click', function (e) {
// 点击那个,那个li就添加active这个类,利用排他
document.querySelector('.active').classList.remove('active')
e.target.classList.add('active')
// 显示对应的内容
contents[e.target.dataset.id].style.zIndex = num++
})
</script>
</body>
</html>
原文链接:https://blog.csdn.net/qq_52845451/article/details/125696218
此处评论已关闭