tab.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Object</title>
<style>
main {
width: 300px;
}
nav {
width: inherit;
height: 30px;
}
nav a, nav span {
display: block;
width: 80px;
height: 30px;
font-size: 14px;
text-decoration: none;
float: left;
color: #fff;
text-align: center;
line-height: 30px;
}
nav a:nth-child(1),
nav span:nth-child(1) {
background: #f47920;
}
nav a:nth-child(2),
nav span:nth-child(2) {
background: #2a5caa;
}
section {
width: inherit;
height: 270px;
background: #65c294;
color: #fff;
font-size: 24px;
}
section:nth-of-type(1) {
display: none;
}
</style>
</head>
<body>
<main class="tab1">
<nav>
<a href="javascript:;">A Home</a>
<a href="javascript:;">A About</a>
</nav>
<section>1</section>
<section>2</section>
</main>
<main class="tab2">
<nav>
<span href="javascript:;">Span Home</span>
<span href="javascript:;">Span About</span>
</nav>
<section>1</section>
<section>2</section>
</main>
<script>
function extend(sub, sup) {
sub.prototype = Object.create(sup.prototype);
Object.defineProperty(sub.prototype, "constructor", {
value: sub,
});
}
function Animation() {}
console.dir(Animation.prototype.constructor);
Animation.prototype.hide = function() {
this.style.display = "none";
}
Animation.prototype.show = function() {
this.style.display = "block";
}
Animation.prototype.background = function(color) {
this.style.backgroundColor = color;
}
function Tab(args) {
args = Object.assign({el: null, link: "a", section: "section", callback: null}, args);
this.tab = document.querySelector(args['el']);
this.links = this.tab.querySelectorAll(args['link']);
this.sections = this.tab.querySelectorAll(args['section']);
this.callback = args['callback'];
}
extend(Tab, Animation);
Tab.prototype.run = function() {
this.bindEvent();
this.reset();
this.action(0);
}
Tab.prototype.bindEvent = function() {
this.links.forEach((el, i) => {
el.addEventListener("click", () => {
this.reset();
this.action(i);
if (this.callback) this.callback();
});
});
}
Tab.prototype.action = function(i) {
this.background.call(this.links[i], '#e67e22');
this.show.call(this.sections[i]);
}
Tab.prototype.reset = function() {
this.links.forEach((el, i) => {
this.background.call(this.links[i], "#95a5a6");
this.hide.call(this.sections[i]);
})
}
new Tab({
el: ".tab1",
callback: function() {
console.log("this is my tab class 1");
},
}).run();
new Tab({
el: ".tab2",
link: "span",
callback: function() {
console.log("this is my tab class 2");
},
}).run();
</script>
</body>
</html>
南无阿弥陀佛