Files
ClassContent/历届学生/罗朝/2019-05-05/tabs.js
2024-09-27 02:06:13 +08:00

104 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 自执行函数
// 形成一个独立的作用域
// 通过原形模拟类
// 注意 以前js没有类的概念现在有
// 以前没有类的概念,但是我们可以通过其他方法来模拟类
// 挂载到window上的方法或者变量都将成为全局变量|方法
(function (bom,dom) {
// 插件的默认配置
var defaultOption = {
// 内容被激活的类名
contentActive: "content_on",
// 标题被激活的类名
titleActive: "title_on",
titleFather: ".tabs_title",
contentFather: ".tabs_content"
};
function tabs(params) {
if(typeof params == "object"
&& params.hasOwnProperty("titleArray")
&& params.hasOwnProperty("contentArray")) {
// 将用户传递过来的参数进行保存,保存到 tabs中
///成tabs的私有属性然后下面的其他方法就可以使用了
this.option = {
titleArray: params.titleArray,
contentArray: params.contentArray
};
// 不必要的参数,如果用户传递了标题和内容的激活类名,那么采用用户的,如果没传
// 那么采取系统默认的
defaultOption.titleActive = params.titleActive || defaultOption.titleActive
defaultOption.contentActive = params.contentActive || defaultOption.contentActive
// 不用 + 进行字符串拼接
this.dom = {
titleFather: document.querySelector(`${defaultOption.titleFather} ul`),
contentFather: document.querySelector(`${defaultOption.contentFather} ul`)
}
this.init();
}else {
//console.error("抱歉,插件运行需要参数")
throw new Error("抱歉,插件运行需要参数");
}
}
tabs.prototype = {
// 插件初始化方法
init() {
this.renderPage();
this.dom.titleChildenli = document.querySelectorAll(`${defaultOption.titleFather} ul li`)
this.dom.contentChildenli = document.querySelectorAll(`${defaultOption.contentFather} ul li`)
this.bindEvent()
},
// 渲染数组成为页面
renderPage() {
var title = "",content="";
for(var i = 0;i<this.option.titleArray.length;i++) {
title += `<li class="${ i == 0 ? defaultOption.titleActive : '' }">${this.option.titleArray[i]}</li>`
content += `<li class="${ i == 0 ? defaultOption.contentActive : '' }">${this.option.contentArray[i]}</li>`
}
this.dom.titleFather.innerHTML = title
this.dom.contentFather.innerHTML = content
},
// es5 老旧的js语法
// es6, 7 => `` let
// babel 将最新的js语法转换为 es5(浏览器能认识的兼容性比较好的)
bindEvent() {
var self = this;
for(let i= 0;i<this.dom.titleChildenli.length;i++) {
this.dom.titleChildenli[i].onmouseover = function () {
for(let j= 0;j<self.dom.titleChildenli.length;j++) {
self.dom.titleChildenli[j].className = ""
self.dom.contentChildenli[j].className = ""
}
self.dom.titleChildenli[i].className = defaultOption.titleActive;
self.dom.contentChildenli[i].className = defaultOption.contentActive;
}
}
}
}
bom.Tabs = tabs
})(window,document)