101 lines
3.1 KiB
JavaScript
101 lines
3.1 KiB
JavaScript
// js 封装插件
|
||
(function () {
|
||
var defaultOption = {
|
||
tabsTitle: "title", // tabs的标题
|
||
}
|
||
// 构造函数,在这里面定义变量,实现插件参数的校验
|
||
function Tabs(option) {
|
||
if (option.hasOwnProperty("el") && option.hasOwnProperty("data")) {
|
||
if (option.el.length !=0 && option.data.length !=0) {
|
||
|
||
defaultOption.tabsTitle = option.tabsTitle || defaultOption.tabsTitle
|
||
|
||
this.option = option
|
||
this.init()
|
||
} else {
|
||
throw new Error("插件需要的核心参数:el和data的数值都不能为空")
|
||
}
|
||
} else {
|
||
// console.error("插件需要的核心参数:el和data都不能为空");
|
||
throw new Error("插件需要的核心参数:el和data都必须传入")
|
||
}
|
||
}
|
||
|
||
// 类的方法,主要实现插件的核心功能
|
||
Tabs.prototype = {
|
||
init: function () {
|
||
this.CreatedTabsTitle();
|
||
},
|
||
// 创建tabs切换的标题
|
||
CreatedTabsTitle: function () {
|
||
var Ul = document.createElement("ul")
|
||
Ul.className = "tabs_title"
|
||
this.option.data.forEach((v,i) => {
|
||
console.log(v);
|
||
Ul.innerHTML += `<li class="${ i == 0 ? 'tabs_title_active' : '' }">${v[defaultOption.tabsTitle]}</li>`
|
||
});
|
||
this.AppendElement(Ul);
|
||
this.CreatedTabsContent();
|
||
|
||
this.BindTabsTitleClick();
|
||
},
|
||
// 为tabs标题绑定事件
|
||
BindTabsTitleClick() {
|
||
var li = document.querySelectorAll(".tabs_title li")
|
||
var tabsContentLi = document.querySelectorAll(".tabs_content li")
|
||
li.forEach((v,i)=>{
|
||
v.onclick = function () {
|
||
li.forEach((k,s)=>{
|
||
k.className = ""
|
||
tabsContentLi[s].className = ""
|
||
});
|
||
v.className = "tabs_title_active"
|
||
tabsContentLi[i].className = "tabs_content_active"
|
||
}
|
||
})
|
||
},
|
||
// 创建tabs切换的内容
|
||
CreatedTabsContent() {
|
||
var Ul = document.createElement("ul")
|
||
Ul.className = "tabs_content";
|
||
this.option.data.forEach((v,i) => {
|
||
var li = document.createElement("li");
|
||
i == 0 ? li.className = "tabs_content_active" : '';
|
||
v.content.forEach((k)=>{
|
||
li.innerHTML += `<div>${k.text}</div>`
|
||
});
|
||
Ul.appendChild(li)
|
||
});
|
||
this.AppendElement(Ul)
|
||
},
|
||
|
||
/**
|
||
* 将html插入到用户指定的父节点中
|
||
* @param {*} html 需要被插入的html
|
||
*/
|
||
AppendElement(html) {
|
||
document.querySelector(this.option.el).appendChild(html)
|
||
}
|
||
}
|
||
|
||
|
||
|
||
// 将自执行函数内部的方法通过全局对象 window 暴露到外面,
|
||
//给用户能使用到
|
||
window.lBtab = Tabs
|
||
})()
|
||
|
||
//es5
|
||
|
||
//es6
|
||
// class
|
||
// class a {
|
||
// constructor() {
|
||
// this.init()
|
||
// }
|
||
|
||
// init() {}
|
||
// }
|
||
|
||
// new a()
|
||
// 语法糖
|