核心原理:排他思想,把所有的相同样式清除, 留下自己
直接上代码
HTML
<!-- tab栏切换 -->
<div class="tab">
<div class="tab_list">
<ul>
<li class="current">水果</li>
<li>蔬菜</li>
<li>饮料</li>
<li>肉</li>
</ul>
</div>
<div class="tab_con">
<div class="item" style="display:block">水果内容</div>
<div class="item">蔬菜内容</div>
<div class="item">饮料内容</div>
<div class="item">肉内容</div>
</div>
</div>
css
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.tab_list>ul {
width: 500px;
display: flex;
}
.tab_list>ul>li {
width: 100px;
height: 50px;
font-size: 15px;
background-color: #ddd;
line-height: 50px;
text-align: center;
margin-right: 30px;
transition: all .4s;
}
.tab_list>ul>li.current {
background-color: #409EFF;
color: #fff;
}
.tab_con>.item {
width: 500px;
height: 120px;
border-top: 1px solid #000;
margin-top: 10px;
display: none;
}
</style>
JS
<script>
// tab栏核心思想利用排它算法
let listItemArr = document.querySelectorAll('li')
let itemArr = document.getElementsByClassName('item')
for (let index = 0; index < listItemArr.length; index++) {
// 循环添加事件
listItemArr[index].onclick = function () {
// 其余人清除 还得用for循环
for (let i = 0; i < listItemArr.length; i++) {
listItemArr[i].className = ''
}
// 留下自己
this.className = 'current'
// 下面的显示内容的模块 其他的隐藏 一种做法
for (let i = 0; i < listItemArr.length; i++) {
itemArr[i].style.display = 'none'
}
itemArr[index].style.display = 'block'
}
}
</script>
实际结果:
