效果图如上, 下面直接放代码
<!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>
.box {
width: 450px;
height: 350px;
margin: 50px auto;
}
.ul1,
.ul2 {
width: 450px;
list-style: none;
margin: 0;
padding: 0;
}
li {
margin: 0;
padding: 0;
text-align: center;
font-size: 30px;
}
.ul1 {
display: flex;
}
.ul1 li {
width: 150px;
height: 50px;
background-color: grey;
line-height: 50px;
}
.ul1 li.active {
background-color: red;
}
.ul2 {
position: relative;
height: 300px;
}
.ul2 li {
width: 450px;
height: 300px;
background-color: purple;
position: absolute;
left: 0;
top: 0;
opacity: 0;
line-height: 300px;
}
.ul2 li.active {
opacity: 1;
}
</style>
</head>
<body>
<div class="box">
<ul class="ul1">
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="ul2">
<li class="active">one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
</body>
</html>
<script>
// 首先获取按钮和标签页
var btns = document.querySelectorAll('.ul1>li')
var views = document.querySelectorAll('.ul2>li')
// 假设一个索引值来表示当前被选中的卡片和按钮
var index = 0
// 先遍历按钮,得到所有按钮
btns.forEach((ele, i) => {
// 给没个按钮添加事件监听
ele.onclick = function () {
// 首先清除按钮和卡片的被选中样式
btns[index].className = ''
views[index].className = ''
// 将当前被选中的按钮和卡片索引值赋值给假设的索引值
index = i
// 再给被选中的索引值添加选中样式的类名
btns[index].className = 'active'
views[index].className = 'active'
}
});
</script>
希望各位大佬发现bug后能提醒本人一下,总感觉这么点代码可能会有遗漏。