iT邦幫忙

2021 iThome 鐵人賽

1
Modern Web

JavaScript 從 50% 開始,打造函式庫不是問題!系列 第 38

JS 38 - 實作 Tab 頁籤

大家好!


樣式


.tabs {
    width: 100%;
    max-width: 60em;
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    border-radius: 0.3125em;
    margin: auto;
    padding: 5em;
    overflow: hidden;
}

.tabs > label {
    flex: 1;
    order: 1;
    background-color: #7de1c8;
    font-weight: bold;
    text-align: center;
    padding: 1em 2em;
    cursor: pointer;
    user-select: none;
    -webkit-tap-highlight-color: transparent;
}

.tabs > label:hover {
    background-color: #c8fae1;
}

.tabs > label.active {
    background-color: transparent;
    cursor: default;
}

.tabs > article {
    flex: 1 1 100%;
    order: 2;
    height: 0;
    padding: 0 2em;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
}

.tabs > label.active + article {
    height: auto;
    padding: 2em;
    opacity: 1;
    visibility: visible;
    transition: padding 0.25s,
                opacity 0.5s 0.25s;
}

程式碼

Felix(window).on('load', function () {
    Felix('.tabs > label').on('click', function () {
        const children = this.parentElement.children;
        Felix.forEach(children, function (el) {
            if (el.tagName !== 'LABEL') return;
            if (el.className.indexOf('active') === -1) return;
            el.classList.remove('active');
        });
        this.classList.add('active');
    });
});

實測

<section class="tabs" data-revealing="float-in bottom">
    <label class="active">HTML</label>
    <article>...</article>
    <label>CSS</label>
    <article>...</article>
    <label>JavaScript</label>
    <article>...</article>
</section>

範例連結製作中。


差不多也到尾聲了。
如果對文章有任何疑問,也歡迎在下方提問和建議!
我是 Felix,我們明天再見!


上一篇
JS 37 - 滾動網頁即自動浮現元素
下一篇
JS 39 - 平滑調整網頁字型大小
系列文
JavaScript 從 50% 開始,打造函式庫不是問題!46
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言