<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多Tab点击切换</title>
<style>
* {
margin: 0;
padding: 0;
}
#tab li {
float: left;
list-style: none;
width: 80px;
height: 40px;
line-height: 40px;
cursor: pointer;
text-align: center;
}
#container {
position: relative;
}
#content1, #content2, #content3 {
width: 300px;
height: 100px;
padding: 30px;
position: absolute;
top: 40px;
left: 0;
}
#tab1, #content1 {
background-color: #ffcc00;
}
#tab2, #content2 {
background-color: #ff00cc;
}
#tab3, #content3 {
background-color: #00ccff;
}
</style>
</head>
<body>
<h2>多Tab点击切换</h2>
<ul id="tab">
<li id="tab1" value="1">10元套餐</li>
<li id="tab2" value="2">30元套餐</li>
<li id="tab3" value="3">50元包月</li>
</ul>
<div id="container">
<div id="content1">
10元套餐详情:<br/> 每月套餐内拨打100分钟,超出部分2毛/分钟
</div>
<div id="content2" style="display: none">
30元套餐详情:<br/> 每月套餐内拨打300分钟,超出部分1.5毛/分钟
</div>
<div id="content3" style="display: none">
50元包月详情:<br/> 每月无限量随心打
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
//方式一:
/* var $container= $("#container>div")
//先获取到所有的li
$("#tab>li").click(function() {//隐式遍历
//显示对应的div
$container.css("display", "none")
//得到当前点击的li在兄弟中的下标
var index = $(this).index();
//找到对应的div并显示
$container[index].style.display = 'block'
})*/
//方式二:效率相对较高,推荐使用
var $container= $("#container>div")
var currentIndex=0;//默认显示的div的下标
//先获取到所有的li
$("#tab>li").click(function() {//隐式遍历
//隐藏当前已经显示的div
$container[currentIndex].style.display = 'none'
//需要显示的div
//得到当前点击的li在兄弟中的下标
var index = $(this).index();
//找到对应的div并显示
$container[index].style.display = 'block'
//更新下标
currentIndex=index;
})
</script>
</body>
</html>
总结:以上两种方式都可以实现我们需要的效果,但是在实际开发中,第二种实现的方式在思想上更加的需要我们取研究,作为一个追求极致的程序员我相信大家更喜欢第二种