思路:
① 遍历Tab选项
② 然后给每个Tab选项绑定点击事件
③ 每次点击时清除所有Tab选项及Tab选项内容的样式,然后给当前Tab选项添加标记样式,给当前Tab选项添加显示样式
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
#tab{
width: 300px;
margin: 30px auto;
}
.tab-nav{
display: flex;
}
.tab-nav a{
flex: 1;
line-height: 40px;
border: 1px solid #000;
text-align: center;
text-decoration: none;
color: #000;}
.tab-nav a.current{
color: #fff;
background: #000;
}
.content{
display: none;
width: 100%;
height: 300px;
color: black;
box-sizing: border-box;
padding: 10px;}
.content.current{
display: block;
}
/*.content1{ background: #6fcaff; }*/
/*.content2{ background: #ffb3e6;}*/
/*.content3{ background: #e0bd7f;}*/
</style> </head>
<body>
<div id="tab">
<!--Tab选项-->
<div class="tab-nav">
<a href="javascript:;" class="current">选项1</a>
<a href="javascript:;">选项2</a>
<a href="javascript:;">选项3</a>
</div>
<!--Tab选项内容-->
<div class="tab-content">
<div class="content content1 current">选项内容1111</div>
<div class="content content2">选项内容2222</div>
<div class="content content3">选项内容3333</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.js"></script>
<script>
// js原生
var tabTotal = document.getElementById('tab');
var tabNav = tabTotal.querySelectorAll('.tab-nav a');
var tabContent = tabTotal.querySelectorAll('.tab-content .content');
for(var i = 0; i < tabNav.length; i++){ // 遍历Tab选项
tabNav[i].onclick = (function (i) { // Tab选项绑定点击事件
return function () {
// 清除所有Tab选项的标记样式
for(var j = 0; j < tabNav.length; j++){
tabNav[j].classList.remove('current');
}
// 给当前选中的tab选项增加样式
tabNav[i].classList.add('current');
// 清除所有Tab选项内容的显示样式
for(j = 0; j < tabContent.length; j++){
tabContent[j].classList.remove('current');
}
tabContent[i].classList.add('current');
}
})(i);
}
// jQuery
$(".tab-nav a").each(function (index) {
$(this).click(function () {
$(this).css({'background':'black','color':'white'}).siblings().css({'background':'white','color':'black'});
$(".content").eq(index).css("display","block").siblings().css("display","none");
})
})
</script>
</body>
</html>