萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 互動特效三合一:摺疊面板、輸入字數統計、分頁切換完整實作

功能模組

  1. 摺疊面板: 點擊導航按鈕切換內容區塊顯示/隱藏,附帶滑動動畫。
  2. 字數即時統計: 模仿微博輸入框,剩餘字數即時顯示,接近上限變紅、超過截斷並提示。
  3. 分頁/標籤切換: 導航按鈕切換對應內容面板,支援搜尋面板顯示/隱藏。

完整單檔案實作

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>jQuery 互動特效三合一</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        .main-box { max-width: 800px; margin: 2rem auto; font-family: sans-serif; }
        .nav-tabs { display: flex; border-bottom: 2px solid #eee; margin-bottom: 1rem; }
        .nav-tabs a { padding: 0.8rem 1.5rem; color: #004499; background: #efefef; text-decoration: none; margin-right: 4px; border-radius: 4px 4px 0 0; }
        .nav-tabs a:hover, .nav-tabs a.on { background: #498cd0; color: #fff; }
        .tab-panel { display: none; padding: 1.5rem; border: 1px solid #eee; border-top: none; border-radius: 0 0 4px 4px; background: #fafafa; }
        .tab-panel:first-of-type { display: block; }
        .table-form th { width: 140px; text-align: right; padding: 8px; color: #777; vertical-align: top; }
        .table-form td { padding: 8px; border-bottom: 1px solid #eee; }
        .table-form input, .table-form select, .table-form textarea { padding: 6px; font-size: 1rem; }
        .char-count { font-weight: 700; font-size: 1.5rem; font-family: Georgia, serif; color: #333; }
        .char-count.warning { color: #ff6b6b; }
        .search-panel { display: none; padding: 1rem; background: #fffbe6; border: 1px solid #ffcc33; margin-bottom: 1rem; border-radius: 4px; }
    </style>
</head>
<body>
    <div class="main-box">
        <!-- 導航分頁 -->
        <nav class="nav-tabs">
            <a href="#" data-tab="panel1" class="on">發布文章</a>
            <a href="#" data-tab="panel2">進階設定</a>
            <a href="#" data-tab="search" class="search-toggle">搜尋文章</a>
        </nav>

        <!-- 搜尋面板 (特殊:toggle 顯示/隱藏) -->
        <div class="search-panel" id="searchPanel">
            <form id="searchForm">
                日期:<input type="date" name="dateMin"> - <input type="date" name="dateMax">
                <select name="channel"><option value="">全部欄目</option></select>
                <select name="field"><option value="">查詢條件</option><option>標題</option><option>作者</option></select>
                <input type="text" name="keyword" placeholder="關鍵字" size="30">
                <button type="submit" class="btn">搜尋</button>
            </form>
        </div>

        <!-- 面板 1:發布文章 -->
        <section class="tab-panel" id="panel1">
            <table class="table-form">
                <tr><th><span class="required">*</span> 標題</th><td><input type="text" name="title" size="60"></td></tr>
                <tr><th>內容</th><td>
                    <textarea name="content" id="content" rows="10" cols="80"></textarea>
                    <div>剩餘字數:<span id="charCount" class="char-count">140</span>/140</div>
                </td></tr>
            </table>
        </section>

        <!-- 面板 2:進階設定 -->
        <section class="tab-panel" id="panel2">
            <table class="table-form">
                <tr><th>封面圖</th><td><input type="file" name="cover"></td></tr>
                <tr><th>標籤</th><td><input type="text" name="tags" placeholder="用逗號分隔"></td></tr>
            </table>
        </section>
    </div>

    <script>
        // ===== 1. 分頁切換 + 搜尋面板 Toggle =====
        $('.nav-tabs a').on('click', function(e) {
            e.preventDefault();
            const $this = $(this);
            const target = $this.data('tab');

            // 搜尋按鈕特殊處理:toggle 面板,不切換主分頁
            if ($this.hasClass('search-toggle')) {
                $('#searchPanel').slideToggle('fast');
                $this.toggleClass('on');
                return;
            }

            // 一般分頁切換
            $('.nav-tabs a').removeClass('on');
            $this.addClass('on');
            $('.tab-panel').hide();
            $('#' + target).fadeIn('fast');
        });

        // ===== 2. 字數統計 (通用函式) =====
        /**
         * 綁定字數限制
         * @param {string} textareaSel - textarea 選擇器
         * @param {string} counterSel - 顯示剩餘字數的 span 選擇器
         * @param {number} max - 最大字數
         */
        function bindCharCounter(textareaSel, counterSel, max) {
            const $ta = $(textareaSel);
            const $counter = $(counterSel);
            $ta.on('input propertychange', function() {
                let val = this.value;
                const len = val.length;
                if (len > max) {
                    val = val.substring(0, max);
                    this.value = val;
                    alert(`超過字數限制 (${max} 字),多出內容已截斷!`);
                }
                const remain = max - val.length;
                $counter.text(remain).toggleClass('warning', remain <= 10);
            });
        }

        // 套用到內容輸入框
        bindCharCounter('#content', '#charCount', 140);

        // ===== 3. 表單送出示範 =====
        $('#searchForm').on('submit', e => {
            e.preventDefault();
            const params = $(e.target).serialize();
            console.log('搜尋參數:', params);
            alert('搜尋參數見 Console');
        });
    </script>
</body>
</html>

核心技術解析

1. .toggle() / .slideToggle() 摺疊動畫

  • 自動處理 display: none/block 切換。
  • 搭配 fadeIn/fadeOut 或 slideDown/slideUp 獲得更豐富動畫。

2. 字數統計通用函式 bindCharCounter

  • 監聽 input (現代) + propertychange (IE 兼容) 事件。
  • 即時計算 val.length,超限自動截斷 substring(0, max)。
  • 倒數 10 字變紅 (CSS .warning),超限 alert 提示。
  • 參數化設計,可同時套用多個輸入框。

3. 分頁切換邏輯

  • 導航按鈕 data-tab 對應面板 id。
  • 點擊時:移除所有 .on、隱藏所有面板、顯示目標面板。
  • 搜尋按鈕獨立邏輯:slideToggle 只控制搜尋面板,不影響主分頁狀態。

無障礙 (a11y) 加強建議

  • 導航改用 <button role="tab" aria-selected="true" aria-controls="panel1"> 語意化標記。
  • 面板加上 role="tabpanel" aria-labelledby="tab1"。
  • 鍵盤支援:←/→ 切換分頁、Enter/Space 啟用。

效能優化

  • 字數統計加 debounce (100-150ms) 避免高頻觸發重排。
  • 面板內容多時改用 display: none 而非 detach() 保留 DOM 狀態。
  • 大型專案建議拆分為獨立模組 (ES Module / AMD) 按需載入。

這三個功能模組涵蓋了後台管理系統 80% 以上的互動需求,掌握核心邏輯後即可靈活組合、擴充成完整的 UI 元件庫。

copyright © 萬盛學電腦網 all rights reserved