/*
这是一个tab选项卡的js,
html代码样式如下:
<ul class="tabs">
<li class="tab">one</li>
<li class="tab">two</li>
<li class="tab">three</li>
</ul>
<div class="tabs-content">
<div class="tab-item">1</div>
<div class="tab-item">2</div>
<div class="tab-item">3</div>
</div>
css代码样式如下:
.tab-item {
display: none;
}
.tab-item.active {
display: block;
}
*/
(function () {
let tabs = document.getElementsByClassName('tabs');
let contents = document.getElementsByClassName('tabs-content');
let lens = tabs.length;
if (lens >= 1) {
let i;
for (i = 0; i <= lens - 1; i++) {
let tab = tabs[i];
let content = contents[i];
bindClick(tab, content);
initTab(tab, content);
}
}
function bindClick(tab, content) {
tab.addEventListener('click', function (e) {
let event = e || window.event;
let target = event.target || event.srcElement;
if (target.nodeName.toLocaleLowerCase() == 'li') {
tabToggle(target, tab, content);
}
})
}
function tabToggle(target, tab, content) {
let index, i;
let tabsList = tab.children;
let contentsList = content.children;
for (i = 0; i <= tabsList.length - 1; i++) {
if (target === tabsList[i]) {
index = i;
}
let menu = tabsList[i];
let panel = contentsList[i];
menu.className = menu.className.replace(' active', '');
panel.className = panel.className.replace(' active', '');
}
tabsList[index].className += ' active';
contentsList[index].className += ' active';
}
function initTab(tab, content) {
let tabsList = tab.children;
let contentsList = content.children;
tabsList[0].className += ' active';
contentsList[0].className += ' active';
}
})()
网友评论