被問到如何在單一 HTML 網頁做出多頁切換效果。

情境是一個只有兩三頁的超迷你網站,一切從簡,想改用單一 HTML 檔打死,但要有點選導覽頁籤切換不同頁面的效果,還必須能用瀏覽器的上一頁下一頁鈕跳轉。

這個需求技術難度不高,只用上古時代的 HTML/JavaScript 規格也能搞定。(查了一下,我真的在十幾年前玩過,不過真要落實 IE 相容得動用 jQuery,2025 年 IE 都滅絕了,還是別為難自己,就用現代 JavaScript 來寫比較輕鬆自在)

點頁籤切換頁面好辦,網頁放多個 div 裝不同頁面內容,用 display: none / block 控制一次只顯示一個。至於回上頁,則可借用 URL 的「#標籤」實作,切換頁面時在 URL 加上 #about、#services、#contact 指定要顯示的頁面,掛載 hashchange 事件在「#標籤」異動時進行切換。瀏覽器歷程記錄會包含 # 變化,如此按上一頁便可回到前一個「#標籤」顯示前一頁面。

我做了一個簡單範例:

程式碼如下,大約 100 行搞定。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>單一 HTML 模擬多頁切換</title>
    <style>
        body {
            margin: 0;
            font-family: 微軟正黑體, Arial, sans-serif;
        }

        header, footer {
            background: #49487a;
            color: #fff;
            padding: 1em 2em;
        }

        header {
            position: relative;
            .logo {
                font-size: 1.5em;
                font-weight: bold;
            }
            nav {
                position: absolute;
                right: 0;
                bottom: 1em;
                a {
                    color: #fff;
                    text-decoration: none;
                    margin-right: 1.5em;
                    font-weight: bold;
                }
            }
        }

        main {
            padding: 2em;
            min-height: 200px;
        }

        footer {
            text-align: center;
            font-size: 0.95em;
        }
    </style>
</head>

<body>
    <header>
        <span class="logo">
            <strong>關洛鷹技術顧問公司</strong>
        </span>
        <nav>
            <a href="#about">關於我們</a>
            <a href="#services">服務項目</a>
            <a href="#contact">連絡方式</a>
        </nav>
    </header>
    <main>
        <section id="about">
            <h2>關於我們</h2>
            <p>我們是一群資深茶包射手組成的技術團隊,您甚至不需開口,我們就知道問題所在,提供您最優質的資訊顧問與系統整合服務。</p>
        </section>
        <section id="services" style="display:none;">
            <h2>服務項目</h2>
            <ul>
                <li>疑難雜症診斷</li>
                <li>系統故障排除</li>
                <li>資訊技術諮詢</li>
                <li>系統架構建議</li>
                <li>系統整合開發</li>
            </ul>
        </section>
        <section id="contact" style="display:none;">
            <h2>連絡方式</h2>
            <p>Email: info@company.com<br>
                電話: (123) 456-7890</p>
        </section>
    </main>
    <footer>
        &copy; 2025 Example Corp. All rights reserved.
    </footer>
    <script>
        // 取得所有切換頁 section id 清單
        const pageIds = [...document.querySelectorAll('main > section')].map(section => section.id);
        function switchPage() {
            // 由 hash 值決定顯示頁面
            const hash = location.hash.replace('#', '') || 'about';
            if (pageIds.includes(hash)) {
                // 切換 section,顯示 is 與 hash 相同者,其餘隱藏
                document.querySelectorAll('main > section').forEach(section => {
                    section.style.display = section.id === hash ? 'block' : 'none';
                });
            }
        }
        window.addEventListener('hashchange', switchPage);
        switchPage();
    </script>
</body>
</html>

除了用香草 JavaScript 自己從頭刻,Bootstrap 的導覽與頁籤也能實現類似的頁面切換,但缺少「#標籤」歷程記錄回上頁的功能,我們可以比照上面的寫法加上。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>單一 HTML 模擬多頁切換 (Bootstrap 版)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            margin: 0;
            font-family: 微軟正黑體, Arial, sans-serif;
        }

        header,
        footer {
            background: #49487a;
            color: #fff;
            padding: 1em 2em;
        }

        header {
            position: relative;
            .logo {
                font-size: 1.5em;
                font-weight: bold;
            }
            .nav {
                position: absolute;
                right: 0;
                bottom: 0.5em;
                button {
                    color: white;
                    &:hover {
                        color: yellow;
                    }
                }
            }   
        }

        main {
            padding: 2em;
            min-height: 250px;
            h2 {
                font-size: 1.4em;
                margin-bottom: 0.5em;
            }
        }

        footer {
            text-align: center;
            font-size: 0.95em;
        }
    </style>
</head>

<body>
    <header>
        <span class="logo">
            <strong>關洛鷹技術顧問公司</strong>
        </span>
        <ul class="nav" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="about-tab" data-bs-toggle="tab" data-bs-target="#about"
                    type="button">關於我們</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="services-tab" data-bs-toggle="tab" data-bs-target="#services" type="button"
                >服務項目</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button"
                >連絡方式</button>
            </li>
        </ul>
    </header>
    <main>
        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="about">
                <h2>關於我們</h2>
                <p>我們是一群資深茶包射手組成的技術團隊,您甚至不需開口,我們就知道問題所在,提供您最優質的資訊顧問與系統整合服務。</p>
            </div>
            <div class="tab-pane fade" id="services">
                <h2>服務項目</h2>
                <ul>
                    <li>疑難雜症診斷</li>
                    <li>系統故障排除</li>
                    <li>資訊技術諮詢</li>
                    <li>系統架構建議</li>
                    <li>系統整合開發</li>
                </ul>
            </div>
            <div class="tab-pane fade" id="contact">
                <h2>連絡方式</h2>
                <p>Email: info@company.com<br>
                    電話: (123) 456-7890</p>
            </div>
        </div>
    </main>
    <footer>
        &copy; 2025 Example Corp. All rights reserved.
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const tabIds = [...document.querySelectorAll('main > .tab-content > .tab-pane')].map(tab => tab.id);
        document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(btn => {
            btn.addEventListener('shown.bs.tab', function (e) {
                location.hash = '#' + e.target.getAttribute('data-bs-target').replace('#', '');
            });
        });
        function activateTabFromHash() {
            const hash = location.hash.replace('#', '') || 'about';
            if (!tabIds.includes(hash)) return;
            const tabBtn = document.querySelector(`button[data-bs-target="#${hash}"]`);
            if (tabBtn && !tabBtn.classList.contains('active')) {
                new bootstrap.Tab(tabBtn).show();
            }
        }
        window.addEventListener('hashchange', activateTabFromHash);
        activateTabFromHash();
    </script>
</body>

</html>

實測效果如下,大家可隨喜選用。

Create multi-page navigation within a single HTML using div elements with display: none/block for page visibility and URL hash for browser navigation. Bootstrap tabs can also achieve this with additional hash support for history navigation.


Comments

Be the first to post a comment

Post a comment