萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 滑動門(Tab 切換)元件:原生 JS 封裝類與現代化架構

什麼是滑動門模式?

滑動門(Sliding Door / Tab Switch)是經典 UI 模式:水平標籤列 + 內容面板,點擊/懸停標籤切換對應面板。廣泛用於產品規格、常見問題、儀表板分頁、後台管理側邊欄。

原始代碼架構分析

  • 使用原型鏈封裝 scrollDoor 類
  • sd(menus, divs, openClass, closeClass) 方法綁定多組標籤/面板
  • onmouseover 事件切換 className 與 display
  • 支援單頁多組實例(m01/m02, mm01/mm02, mmm01/mmm02)

現代化重構:ES6 Class + 無障礙 + 多種觸發模式

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滑動門元件 - 現代實作</title>
    <style>
        * { box-sizing: border-box; }
        body { font: 14px/1.6 system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
        
        .tabs { border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; background: #fff; margin-bottom: 2rem; }
        
        .tab-list { 
            display: flex; 
            background: #f9fafb; 
            border-bottom: 1px solid #e5e7eb;
            overflow-x: auto; /* 手機可滑動 */
        }
        
        .tab-trigger {
            flex: 1 0 auto; min-width: 80px;
            padding: 12px 16px;
            font: inherit; font-weight: 500;
            color: #6b7280; background: transparent;
            border: none; border-bottom: 3px solid transparent;
            cursor: pointer; text-align: center;
            transition: all 0.2s ease;
            position: relative;
        }
        
        .tab-trigger:hover { color: #374151; background: #f3f4f6; }
        .tab-trigger:focus-visible { outline: 2px solid #3b82f6; outline-offset: -2px; z-index: 1; }
        
        .tab-trigger[aria-selected="true"] {
            color: #3b82f6; background: #fff;
            border-bottom-color: #3b82f6;
        }
        .tab-trigger[aria-selected="true"]::before {
            content: ''; position: absolute; top: 0; left: 50%; transform: translateX(-50%);
            width: 80%; height: 3px; background: #3b82f6; border-radius: 3px 3px 0 0;
        }
        
        .tab-panel { 
            display: none; padding: 1.5rem; 
            animation: fadeIn 0.2s ease;
        }
        .tab-panel[hidden] { display: none; }
        .tab-panel:not([hidden]) { display: block; }
        
        @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
        
        .tab-panel h3 { margin-top: 0; color: #1f2937; }
        .tab-panel p { color: #4b5563; }
        
        /* 垂直標籤變體 */
        .tabs.vertical .tab-list { flex-direction: column; border-bottom: none; border-right: 1px solid #e5e7eb; }
        .tabs.vertical .tab-trigger { border-bottom: none; border-right: 3px solid transparent; text-align: left; }
        .tabs.vertical .tab-trigger[aria-selected="true"] { border-right-color: #3b82f6; border-bottom: none; }
        .tabs.vertical .tab-trigger[aria-selected="true"]::before { 
            top: 50%; left: 0; right: auto; transform: translateY(-50%);
            width: 3px; height: 80%; border-radius: 0 3px 3px 0;
        }
    </style>
</head>
<body>
    <!-- 基本水平標籤 -->
    <div class="tabs" id="tabs1" role="tablist" aria-label="產品規格">
        <div class="tab-list">
            <button role="tab" class="tab-trigger" aria-selected="true" aria-controls="panel1-1" id="tab1-1">規格參數</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel1-2" id="tab1-2" tabindex="-1">功能特色</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel1-3" id="tab1-3" tabindex="-1">使用評價</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel1-4" id="tab1-4" tabindex="-1">售後服務</button>
        </div>
        <div role="tabpanel" class="tab-panel" id="panel1-1" aria-labelledby="tab1-1"><h3>規格參數</h3><p>尺寸:150×80×12mm|重量:180g|電池:4500mAh</p></div>
        <div role="tabpanel" class="tab-panel" id="panel1-2" aria-labelledby="tab1-2" hidden><h3>功能特色</h3><p>支援 5G、WiFi 6、NFC、IP68 防水</p></div>
        <div role="tabpanel" class="tab-panel" id="panel1-3" aria-labelledby="tab1-3" hidden><h3>使用評價</h3><p>4.8/5 星,用戶稱讚續航優異</p></div>
        <div role="tabpanel" class="tab-panel" id="panel1-4" aria-labelledby="tab1-4" hidden><h3>售後服務</h3><p>一年保固、7-11 取貨退換貨</p></div>
    </div>
    
    <!-- 懸停觸發模式 -->
    <div class="tabs" id="tabs2" data-trigger="hover" role="tablist" aria-label="快速預覽">
        <div class="tab-list">
            <button role="tab" class="tab-trigger" aria-selected="true" aria-controls="panel2-1" id="tab2-1">圖片 1</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel2-2" id="tab2-2" tabindex="-1">圖片 2</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel2-3" id="tab2-3" tabindex="-1">圖片 3</button>
        </div>
        <div role="tabpanel" class="tab-panel" id="panel2-1" aria-labelledby="tab2-1"><img src="https://picsum.photos/400/200?1" alt="圖片1" style="width:100%;border-radius:4px"></div>
        <div role="tabpanel" class="tab-panel" id="panel2-2" aria-labelledby="tab2-2" hidden><img src="https://picsum.photos/400/200?2" alt="圖片2" style="width:100%;border-radius:4px"></div>
        <div role="tabpanel" class="tab-panel" id="panel2-3" aria-labelledby="tab2-3" hidden><img src="https://picsum.photos/400/200?3" alt="圖片3" style="width:100%;border-radius:4px"></div>
    </div>
    
    <!-- 垂直標籤 -->
    <div class="tabs vertical" id="tabs3" role="tablist" aria-label="設定選單" style="max-width: 600px;">
        <div class="tab-list">
            <button role="tab" class="tab-trigger" aria-selected="true" aria-controls="panel3-1" id="tab3-1">帳號設定</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel3-2" id="tab3-2" tabindex="-1">隱私權</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel3-3" id="tab3-3" tabindex="-1">通知偏好</button>
            <button role="tab" class="tab-trigger" aria-selected="false" aria-controls="panel3-4" id="tab3-4" tabindex="-1">帳單資訊</button>
        </div>
        <div role="tabpanel" class="tab-panel" id="panel3-1" aria-labelledby="tab3-1"><h3>帳號設定</h3><p>修改信箱、密碼、雙因子驗證</p></div>
        <div role="tabpanel" class="tab-panel" id="panel3-2" aria-labelledby="tab3-2" hidden><h3>隱私權</h3><p>資料收集、廣告個人化、第三方共享</p></div>
        <div role="tabpanel" class="tab-panel" id="panel3-3" aria-labelledby="tab3-3" hidden><h3>通知偏好</h3><p>Email、推播、簡訊通知設定</p></div>
        <div role="tabpanel" class="tab-panel" id="panel3-4" aria-labelledby="tab3-4" hidden><h3>帳單資訊</h3><p>訂閱方案、付款方式、發票設定</p></div>
    </div>

    <script>
        class TabComponent {
            constructor(container) {
                this.container = container;
                this.triggers = [...container.querySelectorAll('[role="tab"]')];
                this.panels = [...container.querySelectorAll('[role="tabpanel"]')];
                this.triggerMode = container.dataset.trigger || 'click'; // 'click' | 'hover' | 'auto'
                this.activationDelay = 150; // hover 延遲(ms)
                this.hoverTimer = null;
                this.init();
            }
            
            init() {
                // 驗證結構
                if (this.triggers.length !== this.panels.length) {
                    console.error('TabComponent: 觸發器與面板數量不符');
                    return;
                }
                
                // 建立 ID 關聯(若缺失)
                this.triggers.forEach((trigger, i) => {
                    const panel = this.panels[i];
                    if (!trigger.id) trigger.id = `tab-${this.container.id}-${i}`;
                    if (!panel.id) panel.id = `panel-${this.container.id}-${i}`;
                    trigger.setAttribute('aria-controls', panel.id);
                    panel.setAttribute('aria-labelledby', trigger.id);
                });
                
                this.bindEvents();
                this.updateAria(this.getActiveIndex());
            }
            
            bindEvents() {
                this.triggers.forEach((trigger, i) => {
                    if (this.triggerMode === 'hover') {
                        trigger.addEventListener('mouseenter', () => this.activateWithDelay(i));
                        trigger.addEventListener('mouseleave', () => this.clearHoverTimer());
                        // 面板也保持 hover 狀態
                        this.panels[i].addEventListener('mouseenter', () => this.clearHoverTimer());
                        this.panels[i].addEventListener('mouseleave', () => this.activateWithDelay(this.getActiveIndex()));
                    } else {
                        trigger.addEventListener('click', () => this.activate(i));
                    }
                    
                    // 鍵盤導航(所有模式通用)
                    trigger.addEventListener('keydown', e => this.onKeydown(e, i));
                });
                
                // 點擊外部關閉(可選)
                // document.addEventListener('click', e => { if (!this.container.contains(e.target)) this.deactivateAll(); });
            }
            
            onKeydown(e, index) {
                const len = this.triggers.length;
                let newIndex = index;
                
                if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                    e.preventDefault(); newIndex = (index + 1) % len;
                } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                    e.preventDefault(); newIndex = (index - 1 + len) % len;
                } else if (e.key === 'Home') {
                    e.preventDefault(); newIndex = 0;
                } else if (e.key === 'End') {
                    e.preventDefault(); newIndex = len - 1;
                } else if (e.key === 'Enter' || e.key === ' ') {
                    if (this.triggerMode !== 'click') { e.preventDefault(); this.activate(index); }
                    return;
                } else {
                    return;
                }
                
                this.activate(newIndex);
                this.triggers[newIndex].focus();
            }
            
            activateWithDelay(index) {
                this.clearHoverTimer();
                this.hoverTimer = setTimeout(() => this.activate(index), this.activationDelay);
            }
            
            clearHoverTimer() {
                if (this.hoverTimer) { clearTimeout(this.hoverTimer); this.hoverTimer = null; }
            }
            
            activate(index) {
                this.clearHoverTimer();
                if (index < 0 || index >= this.triggers.length) return;
                this.updateAria(index);
            }
            
            deactivateAll() {
                this.triggers.forEach(t => t.setAttribute('aria-selected', 'false'));
                this.panels.forEach(p => p.hidden = true);
            }
            
            updateAria(activeIndex) {
                this.triggers.forEach((t, i) => {
                    const selected = i === activeIndex;
                    t.setAttribute('aria-selected', selected);
                    t.tabIndex = selected ? 0 : -1;
                });
                this.panels.forEach((p, i) => p.hidden = i !== activeIndex);
            }
            
            getActiveIndex() {
                return this.triggers.findIndex(t => t.getAttribute('aria-selected') === 'true');
            }
            
            // 公開 API
            next() { this.activate((this.getActiveIndex() + 1) % this.triggers.length); }
            prev() { this.activate((this.getActiveIndex() - 1 + this.triggers.length) % this.triggers.length); }
            goTo(index) { this.activate(index); }
            destroy() { this.clearHoverTimer(); /* 移除事件監聽器 */ }
        }
        
        // 自動初始化所有 .tabs
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('.tabs').forEach(el => new TabComponent(el));
        });
    </script>
</body>
</html>

架構對比

特性原版 scrollDoor現代 TabComponent
架構Prototype 類ES6 Class + 私有欄位
觸發模式僅 mouseoverclick / hover / auto 可配置
無障礙無完整 ARIA (tablist, tab, tabpanel, aria-selected, aria-controls)
鍵盤導航無Arrow keys, Home, Enter, Tab 完整支援
多實例手動 new 多次自動掃描 .tabs 初始化
動畫無(display 切換)CSS fadeIn + 邊框滑動
響應式無flex-wrap, 橫向滾動, 垂直模式
記憶體管理無銷毀提供 destroy()

進階功能擴充

1. URL Hash 同步(可分享連結直達分頁)

class TabComponent {
    // ... 在 activate() 中添加
    activate(index) {
        // ...
        const trigger = this.triggers[index];
        const hash = trigger.dataset.hash || trigger.id;
        if (hash) history.replaceState(null, '', `#${hash}`);
    }
    
    init() {
        // 載入時檢查 hash
        const hash = location.hash.slice(1);
        if (hash) {
            const idx = this.triggers.findIndex(t => t.dataset.hash === hash || t.id === hash);
            if (idx >= 0) this.activate(idx);
        }
        window.addEventListener('hashchange', () => {
            const hash = location.hash.slice(1);
            const idx = this.triggers.findIndex(t => t.dataset.hash === hash || t.id === hash);
            if (idx >= 0) this.activate(idx);
        });
    }
}

2. 懶載入面板內容

<div role="tabpanel" class="tab-panel" id="panel-heavy" aria-labelledby="tab-heavy" hidden data-src="/api/heavy-content"></div>

// 在 activate() 時
const panel = this.panels[index];
if (panel.dataset.src && !panel.dataset.loaded) {
    fetch(panel.dataset.src).then(r => r.text()).then(html => {
        panel.innerHTML = html;
        panel.dataset.loaded = 'true';
    });
}

3. 動態增減標籤

addTab(label, content, index = this.triggers.length) {
    // 建立 trigger & panel 元素
    // 插入 DOM
    // 重新初始化索引
    // 更新 ARIA
}
copyright © 萬盛學電腦網 all rights reserved