css部分
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.box {
margin: 20px auto;
width: 500px;
}
.box .tab {
position: relative;
top: 1px;
display: flex;
justify-content: flex-start;
align-items: center;
}
.box .tab li {
box-sizing: border-box;
margin-right: 15px;
padding: 0 20px;
height: 35px;
line-height: 33px;
border: 1px solid #CCC;
background: #DDD;
color: #555;
font-size: 14px;
cursor: pointer;
}
.box .tab li.active {
background: #FFF;
font-weight: 700;
border-bottom-color: #FFF;
}
.box .content div {
display: none;
box-sizing: border-box;
padding: 15px;
height: 200px;
border: 1px solid #CCC;
}
.box .content div.active {
display: block;
}
</style>
<body>
<div class="box" id="box">
<ul class="tab">
<li class="active">音乐</li>
<li>电影</li>
<li>动漫</li>
</ul>
<div class="content">
<div class="active">达拉崩吧...</div>
<div>我的姐姐</div>
<div>斗罗大陆</div>
</div>
</div>
</body>
升级版
<script>
//获取元素
var box = document.querySelector('#box'),
tabList = box.querySelectorAll('.tab>li'),
conList = box.querySelectorAll('.content>div')
// 封装一个方法:点击的是哪一个「点击那一项的索引传递进来」,
首先把所有的LI/DIV都清除选中样式,然后再告诉我这一个有选中的样式...
function changeTab(index) {
for (var i = 0
tabList[i].className = ''
conList[i].className = ''
}
tabList[index].className = 'active'
conList[index].className = 'active'
}
// 循环所有LI,分别给每一个LI绑定点击事件,当点击某个LI的时候,执行changeTab,
并且传递对应索引
for (var i = 0
tabList[i].myIndex = i
tabList[i].onmouseover = function () {
changeTab(this.myIndex)
}
}
</script>
终极进化版
<script>
var box = document.querySelector('#box'),
tabList = box.querySelectorAll('.tab>li'),
conList = box.querySelectorAll('.content>div')
// prevIndex:上一个选中LI的索引,初始值是零,因为最开始选中的是第一个
var prevIndex = 0
for (var i = 0
tabList[i].myIndex = i
tabList[i].onmouseover = function () {
// this.myIndex:当前点击这一项的索引
var curIndex = this.myIndex
// 4.如果当前操作的这一项和选中的这一项是同一项,则无需做任何的处理
if (curIndex === prevIndex) return
// 1.操作的是谁,就让谁有选中样式
tabList[curIndex].className = conList[curIndex].className = 'active'
// 2.之前选中的是谁,就让他没有选中样式
tabList[prevIndex].className = conList[prevIndex].className = ''
// 3.当前操作的索引是下一次操作的“上一次索引”
prevIndex = curIndex
}
}
</script>