需求:
+ 点击哪一个按钮的时候, 切换对应的 按钮高亮, 和盒子显示
+ 例子: 当你点击 1号按钮 的时候
=> 1号按钮有 active 类名, 2号按钮和3号按钮没有 active 类名
=> 1号盒子有 active 类名, 2号盒子和2号盒子没有 active 类名
+ 例子: 当你点击 2号按钮 的时候
=> 2号按钮有 active 类名, 1号按钮和3号按钮没有 active 类名
=> 2号盒子有 active 类名, 1号盒子和2号盒子没有 active 类名
代码实现:
1. 获取元素
=> btns, 表示所有 ul 下面的 li, 也就是所有按钮
=> boxs, 表示所有 ol 下面的 li, 也就是所有盒子
2. 绑定点击事件
=> 给 btns 里面的每一个按钮, 绑定点击事件
=> 因为点击每一个按钮的时候, 执行切换操作
3. 拿到我点击的这个 li 的索引是多少
=> 当你点击 1号 按钮的时候, 1号按钮和1号盒子都有 active
=> 你需要直到你点击的这个 li 的索引是多少
=> [ btn1, btn2, btn3, btn4 ]
[ box1, box2, box3, box4 ]
=> 在循环绑定点击事件的时候
-> 顺便把索引记录在元素身上
4. 切换类名
=> 把所有元素的类名都去掉, 单独给我当前点击的这一个加上
// ulList是 选项按钮,boxs是 卡内容
let ulList = document.querySelectorAll('ul>li')
let boxs = document.querySelectorAll('ol>li')
ulList.forEach((item, index) => {
item.onclick = () => {
for (let i = 0; i < ulList.length; i++) {
ulList[i].className = boxs[i].className = ''
}
ulList[index].className = boxs[index].className = 'active'
}
})
<div class="box" id="box">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
* {
margin: 0;
padding: 0;
}
.box {
width: 600px;
height: 350px;
border: 10px solid pink;
margin: 30px auto;
display: flex;
flex-direction: column;
}
.box > ul {
height: 80px;
display: flex;
}
.box > ul > li {
flex: 1;
background-color: skyblue;
color: #fff;
font-size: 34px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.box > ul > li.active {
background-color: orange;
}
.box > ol {
flex: 1;
position: relative;
}
.box > ol > li {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
display: none;
justify-content: center;
align-items: center;
background-color: purple;
color: #fff;
font-size: 100px;
}
.box > ol > li.active {
display: flex;
}