<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡</title>
</head>
<style type="text/css">
*{
margin:0;
padding: 0;
}
li{
list-style:none;
}
.tab-top{
width: 400px;
height: 40px;
margin: 20px auto 0;
}
.tab-top ul li{
float: left;
width: 100px;
line-height: 40px;
text-align: center;
cursor: pointer;
}
.tab-top ul li.selected {
color: #fff;
background: #f60;
}
.tab-content {
width: 400px;
height: 300px;
border: 1px solid #ddd;
margin: 10px auto 0;
}
.tab-content > div {
display: none;
}
</style>
<body>
<div class="tab-top">
<ul>
<li class="selected">选项卡1</li>
<li>选项卡2</li>
<li>选项卡3</li>
</ul>
</div>
<div class="tab-content">
<div style="display: block;">内容1</div>
<div>内容2</div>
<div>内容3</div>
</div>
</body>
<script type="text/javascript" src="./vue.min.js"></script>
<script type="text/javascript">
var Tab = (function() {
//1. 构造函数
function Obj(option) {
// 数据的获取和健壮性处理
this.aTabList = option.aTabList
this.aTabCount = option.aTabCount
this.eventType = option.eventType || 'click'
this.curIndex = option.curIndex || 0
this.callback = option.callback || null
this.Len = this.aTabList.length
if (this.curIndex < 0) {
this.curIndex = 0;
}
if (this.curIndex > this.Len - 1) {
this.curIndex = this.Len - 1;
}
if (!this.aTabList || !this.aTabCount) {
throw new Error('组件参数有误');
}
}
//2. 原型对象
Obj.prototype = {
constructor: Obj,//手动修正构造函数的指针
install: function() {// 真正组件的入口方法
// 最好都是方法的调用
// 选项卡的初始化
this.cutTabStyle();
this.cutTabCount();
// 事件绑定
this.bindEvent();
},
cutTabStyle: function(){
// 顶部选项栏的切换,遍历除去selected,给目前所选加上selected
for (var i = 0; i < this.Len; i++){
this.aTabList[i].classList.remove('selected');
}
this.aTabList[this.curIndex].classList.add('selected');
},
cutTabCount: function(){
// 内容区域的切换,遍历除去内容,给目前所选加上内容
for (var i = 0; i < this.Len; i++){
this.aTabCount[i].style.display = 'none';
this.aTabCount[this.curIndex].style.display = 'block';
}
},
bindEvent: function() {
var _this = this;
// 用 for 循环对其进行事件绑定
for (var i = 0; i < this.Len; i++){
//添加属性
this.aTabList[i].index = i;
this.aTabList[i]['on' + this.eventType] = function(ev){
ev.stopPropagation();
// 核心 -> 获取到当前索引
_this.curIndex = this.index;
_this.cutTabStyle();
_this.cutTabCount();
// 执行回调
_this.callback && _this.callback(_this.curIndex);
}
}
}
}
//3. 返回对象, 公开接口
return Obj;
})();
// 创建实例化对象
// 传入json对象
var obj = new Tab({
aTabList: document.querySelectorAll('.tab-top > ul > li'),
aTabCount: document.querySelectorAll('.tab-content > div'),
eventType: 'click', // 可选的
curIndex: 0,//可选的
callback: function(v) {
console.log(v)
}
});
obj.install();
</script>
</html>