原生js的tab栏切换
布局
<div class='tab'>
<div class='tab_list'>
<ul>
<li class='current'>推荐</li>
<li>排行榜</li>
<li>歌单</li>
<li>主播电台</li>
<li>歌手</li>
<li>新碟上架</li>
</ul>
</div>
<div class='tab_con'>
<div class="item one" style='display:block'>歌曲推荐</div>
<div class="item two">排行榜</div>
<div class="item three">热门歌单</div>
<div class="item four">主播电台</div>
<div class="item five">歌手排行榜</div>
<div class="item six">新碟上架</div>
</div>
</div>
获取dom元素
//拿到上面的tab栏
var tabList = document.querySelector('.tab_list');
//获取所有的li
var lis = tabList.querySelectorAll('li');
//拿到下方的所有item
var items = document.querySelectorAll('.item');
js逻辑部分
//每个li对应的点击事件
for (var i = 0; i < lis.length; i++) {
//自定义下标属性
lis[i].setAttribute('index', i);
//每个tab栏的点击事件
lis[i].onclick = function () {
for (var i = 0; i < lis.length; i++) {
//排他思想,把其它的都置空
lis[i].className = '';
}
//留下当前的
this.className = 'current';
//下面显示内容模块
var index = this.getAttribute('index');
for (var i = 0; i < items.length; i++) {
//去掉其他的 item,让这些隐藏起来
items[i].style.display = 'none';
}
//只留下当前的 item,让它显示出来
items[index].style.display = 'block';
}
}
css部分
* {
margin: 0;
padding: 0;
}
.tab {
width: 800px;
height: 45px;
border: 1px solid #c81623;
background: #c81623;
position: relative;
margin: 100px auto;
}
.tab_list li {
width: 160px;
height: 45px;
list-style: none;
line-height: 45px;
text-align: center;
float: left;
}
.tab_list .current {
background-color: #000;
color: #fff;
border-radius: 16px;
width: 70px;
height: 40px;
opacity: 0.2;
}
.item {
width: 800px;
height: 200px;
padding-top: 40px;
font-size: 30px;
color: #000;
text-align: center;
background: #efefef;
top: 47px;
position: absolute;
}
效果
vue.js的tab栏切换
视图区域
var app = new Vue({
el: '#tab',
data: {
tabs: ["推荐", "排行榜", "歌单", "主播电台", "歌手"],
tabContents: ["歌曲推荐", "排行榜", "热门歌单", "主播电台", "歌手排行榜"],
num: 1
}
})
布局
<div id="tab">
<ul>
<li v-for="(item,index) in tabs" :class="{active:index == num}" @click="tab(index)">{{item}}</li>
</ul>
<div class="item">
<div v-for='(item,index) in tabContents' v-show=" index == num">{{item}}</div>
</div>
</div>
方法
methods: {
tab(index) {
this.num = index;
}
}
css部分
* {
margin: 0;
padding: 0;
}
ul {
width: 800px;
height: 45px;
border: 1px solid #c81623;
border-bottom: 1px solid #c81623;
background: #fafafa;
position: relative;
margin: 100px auto;
}
ul li {
width: 160px;
height: 45px;
list-style: none;
line-height: 45px;
text-align: center;
float: left;
}
.item {
width: 800px;
height: 200px;
padding-top: 40px;
font-size: 30px;
color: #fff;
text-align: center;
text-shadow: 2px 2px 4px #000000;
background: #efefef;
top: 147px;
left: 283px;
position: absolute;
}
效果如下
总结:
原生js和vue.js的tab切换都是利用循环遍历找到对应下标对应的内容,不同的是原生的js利用排他思想进行选中当前的tab栏,而vue.js直接可以用v-for进行数组的遍历。