很簡單的一個demo,平時經常用到,整理下,每次用直接複製粘貼挺香的。
DEMO下載 https://download.csdn.net/download/tianpeng1996/12535658
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQ實現選項卡-鵬仔先生</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
body{
padding: 300px;
box-sizing: border-box;
}
.tab-box{
width: 500px;
display: flex;
align-items: center;
}
.tab-box span{
color: #fff;
font-size: 16px;
line-height: 30px;
text-align: center;
display: inline-block;
width: 100px;
background: #000;
cursor: pointer;
}
.tab-box .active{
background: skyblue;
}
.content div{
display: none;
}
.content .active{
display: block;
}
</style>
</head>
<body>
<div class="tab-box">
<span class="active">tab-1</span>
<span>tab-2</span>
<span>tab-3</span>
<span>tab-4</span>
<span>tab-5</span>
</div>
<div class="content">
<div class="active">內容1</div>
<div>內容2</div>
<div>內容3</div>
<div>內容4</div>
<div>內容5</div>
</div>
</body>
</html>
<script>
$(".tab-box span").click(function(){
// 給當前的添加類名,並清除同級其他的類名
$(this).addClass("active").siblings().removeClass("active");
// 獲取當前點擊的索引
var index = $(this).index();
// 對應索引對應的添加類名active,並清楚同級其他的類名
$(this).parent().siblings().children().eq(index).addClass("active").siblings().removeClass("active");
})
// 前端共享博客 http://sharedblog.cn
// 作者:鵬仔先生
</script>
前端共享博客 http://sharedblog.cn
鵬仔資源網 http://iqzhan.com