<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="./TabsController.js"></script>
<style> ul, li { list-style: none; margin: 0; padding: 0; } .tab .tab-bar { display: flex; border-bottom: 1px solid blue; } .tab .tab-bar li { margin: 3px 20px 0 0; width: 30px; text-align: center; } .tab .tab-bar li.active { border: 1px solid blue; border-bottom: none; } .tab .tab-content li { display: none; } .tab .tab-content li.active { display: block; } </style>
</head>
<body>
<div class="tab">
<ul class="tab-bar">
<li>
1
</li>
<li>
2
</li>
<li>
3
</li>
</ul>
<ul class="tab-content">
<li>content1</li>
<li>content2</li>
<li>content3</li>
</ul>
</div>
</body>
<script> new TabsController(document.querySelector(".tab")); </script>
</html>
/** *自己封装的一个基础的Tabs组件 *使用时只需要在页面引入js然后将html中div.tab复制,使用new TabsController(element)即可 */
class TabsController {
constructor(element) {
this.nav = element.querySelector(".tab-bar").children;
this.content = element.querySelector(".tab-content").children;
this.active = 1; //当前激活的标签
this.init(); //初始化
this.bindEvents(); //绑定事件
}
init() {
this.nav[0].classList.add("active");
this.content[0].classList.add("active");
}
bindEvents() {
//封装foreach方法用来遍历节点
const forEach = (context, fn) => Array.prototype.forEach.call(context, fn);
//封装indexOf方法用来判断当前节点在父节点的中的次序
const indexOf = (context, item) =>
Array.prototype.indexOf.call(context, item);
forEach(this.nav, i => {
i.addEventListener("click", e => {
forEach(this.nav, i => i.classList.remove("active"));
forEach(this.content, i => i.classList.remove("active"));
this.active = indexOf(this.nav, e.target);
this.nav[this.active].classList.add("active");
this.content[this.active].classList.add("active");
});
});
}
}
还没有评论,来说两句吧...