html样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#tab{
width: 300px;
height: 200px;
border: 1px solid;
border-radius: 5px;
margin: 50px auto;
}
ul{
height: 50px;
border-bottom: #888 solid 1px;
list-style: none;
display: flex;
}
li{
flex-grow: 1;
text-align: center;
line-height: 50px;
cursor: pointer;
}
li.active{
background: orangered;
color: white;
}
.content{
display: flex;
}
.content .item{
flex-grow: 1;
text-align: center;
line-height: 40px;
visibility: hidden;
}
.content .item.active{
visibility: visible;
}
</style>
</head>
<body>
<div id="tab">
<ul>
<li class = "active">选项卡标题1</li>
<li>选项卡标题2</li>
</ul>
<div class="content">
<div class = "item active">选项卡内容1</div>
<div class="item">选项卡内容2</div>
</div>
</div>
<script src="./js/libs/jQuery/jquery.js"></script>
<script src="./js/jquery.tab.js"></script>
<script>
$(function(){
$("#tab").tab()
})
</script>
</body>
</html>
<script src="./js/libs/jQuery/jquery.js"></script>为引入的jQuery库
<script src="./js/jquery.tab.js"></script>为引入的自己封装的插件
js代码
;(function($){
$.fn.extend({
"tab":function(){
this.click(function(e){
// 高亮选项卡标题
$(this).find("li").removeClass("active")
// 获取被点击到的li
$(e.target).addClass("active")
// 展示对应内容
$(".item").removeClass("active")
var index = $(e.target).index($(this).find("li"))
$(".item").eq(index).addClass("active")
})
}
})
}(jQuery))
/***************************************
<div id="tab">
<ul>
<li class = "active">选项卡标题</li>
<li class = "active">选项卡标题</li>
</ul>
<div>
<div class = "active">选项卡内容</div>
<div class = "active">选项卡内容</div>
</div>
</div>
***************************************/
利用自执行函数+闭包函数避免全局污染