现在来一个小练习,就是用js实现多tab之间的切换:
<body>
<ul id="tab">
<li id="tab1">10元套餐</li>
<li id="tab2">20元套餐</li>
<li id="tab3">30元套餐</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>
</body>
对应的css格式如图:
<style type="text/css">
* {
margin: 0;
padding: 0;
} #tab>li {
float: left;
list-style: none;
width: 80px;
height: 40px;
text-align: center;
line-height: 40px;
cursor: pointer;
border: 1px gray solid;
border-collapse: collapse;
} #tab>li:nth-child(1) {
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
} #tab>li:nth-last-child(1) {
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
} #content1,
#content2,
#content3 {
width: 300px;
height: 100px;
padding: 30px;
position: absolute;
top: 40px;
left: 0px;
border-radius: 10px;
} #tab1,
#content1 {
background: orangered;
} #tab2,
#content2 {
background: pink;
} #tab3,
#content3 {
background: deeppink;
}
</style>
效果图:
js实现的结果:
<script src="../../../js/jquery-1.10.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() { var currentindex = 0;
var $contents = $("#container>div");
$("#tab>li").click(function() {
$contents[currentindex].style.display = "none";
var index = $(this).index();
$contents[index].style.display = "block";
currentindex = index;
}) })
</script>
可以实现正常的切换了。