<---- 结构部分 ----->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/index.css">
<title>Document</title>
</head>
<body>
<div class="tab J_tab">
<div class="nav">
<div class="nav-item current">选项一</div>
<div class="nav-item">选项二</div>
<div class="nav-item">选项三</div>
</div>
<div class="page">
<div class="page-item current">页面一</div>
<div class="page-item">页面二</div>
<div class="page-item">页面三</div>
</div>
</div>
<script src="js/index.js"></script>
<script type="text/javascript">
var tab = new Tab().init()
</script>
</body>
</html>
; (function (doc) {
var Tab = function () {
var oTab = doc.getElementsByClassName('J_tab')[0],
oPage = doc.getElementsByClassName('page')[0];
this.oNav = oTab.getElementsByClassName('nav')[0];
this.oNavItems = this.oNav.getElementsByClassName('nav-item');
this.oPageItems = oPage.getElementsByClassName('page-item');
this.curIdx = 0;
}
Tab.prototype.init = function () {
this.bandEvent();
}
Tab.prototype.bandEvent = function () {
this.oNav.addEventListener('click', this.onNavClick.bind(this), false)
}
Tab.prototype.onNavClick = function (ev) {
var e = ev || window.event,
tar = e.target || e.srcElement,
className = tar.className;
if (className === 'nav-item') {
this.setCurrent(this.curIdx, 'remove')
this.curIdx = [].indexOf.call(this.oNavItems, tar);
this.setCurrent(this.curIdx, 'add')
}
}
Tab.prototype.setCurrent = function(index, field) {
switch(field) {
case 'add':
this.oPageItems[index].className += ' current';
this.oNavItems[index].className += ' current';
break;
case 'remove':
this.oPageItems[index].className = 'page-item';
this.oNavItems[index].className = 'nav-item';
break;
default:
break;
}
}
window.Tab = Tab
})(document)
.tab {
width: 500px;
height: 500px;
margin: 50px auto;
border: 1px solid #000;
}
.tab .nav {
height: 50px;
border-bottom: 1px solid #000;
}
.tab .nav-item {
width: 33.33%;
float: left;
height: 100%;
text-align: center;
line-height: 50px;
}
.tab .nav .current {
background: #000;
color: #fff;
}
.tab .page {
position: relative;
height: 450px;
}
.tab .page-item {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
text-align: center;
line-height: 450px;
font-size: 100px;
display: none;
}
.tab .page .current {
display: block;
}