美文网首页
Js原生的Tab选项卡组件

Js原生的Tab选项卡组件

作者: 国酱 | 来源:发表于2019-05-21 16:59 被阅读0次
/*
    这是一个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';
    }
})()

相关文章

网友评论

      本文标题:Js原生的Tab选项卡组件

      本文链接:https://www.haomeiwen.com/subject/kmgjzqtx.html