DIV CSS 佈局教程網

用 JS 與 DIV 做出滑鼠移入即切換的標籤頁
編輯:關於JavaScript     

「滑過就換內容」的標籤式切換,本質上是「把一組元素全部隱藏,只顯示指定那一個」。做法可以很簡單,也可以很謹慎——差別在於可讀性、無障礙與維護成本。

原始範例

<html>
<head>
<title>DIV 層切換</title>
<script language="JavaScript" type="text/javascript">
/*********************************************
 * 功能:通用 DIV 切換函式
 * 參數:
 *   divID     - 要顯示的 DIV 編號
 *   divName   - 這一組 DIV 的共同命名前綴
 *   zDivCount - 這一組 DIV 的數量減一
 *********************************************/
function ChangeDiv(divId, divName, zDivCount) {
    for (var i = 0; i <= zDivCount; i++) {
        document.getElementById(divName + i).style.display = "none";
    }
    document.getElementById(divName + divId).style.display = "block";
}
</script>
</head>
<body>
層切換示例:
<span onMouseMove="JavaScript:ChangeDiv('0','JKDiv_',2)" style="cursor:hand;">內容一</span>
<span onMouseMove="JavaScript:ChangeDiv('1','JKDiv_',2)" style="cursor:hand;">內容二</span>
<span onMouseMove="JavaScript:ChangeDiv('2','JKDiv_',2)" style="cursor:hand;">內容三</span>

<div id="BigDIV" style="border:solid 1px #cccccc;width:460px;margin:10px;">
  <div id="JKDiv_0" style="font-size:14px;margin:20px;color:#FF0000;">
    內容部分第一區<br><img src="images/common/watermark.gif">
  </div>
  <div id="JKDiv_1" style="display:none;font-size:14px;margin:10px;color:#FF0000;">
    內容部分第二區<br><img src="logo.gif">
  </div>
  <div id="JKDiv_2" style="display:none;font-size:14px;margin:10px;color:#FF0000;">
    內容部分第三區
  </div>
</div>
</body>
</html>

這個寫法可以改進的地方

1. 標籤沒有語意。用 span 加 onmousemove 當切換器,螢幕閱讀器完全不會把它當成可操作的控制項,鍵盤使用者也無法聚焦。應該改用 button 或具備 role="tab" 的元素。

2. 用 onmousemove 會誤觸。滑鼠只是路過就會切換,使用者想移到别的地方時內容已經跳掉了。改用 click 更可控;若真要 hover 切換,至少加一點延遲。

3. 元素數量寫死。得手動傳 zDivCount,新增一頁就要改所有呼叫處。

4. display:none 對螢幕閱讀器不友善。切換後焦點沒有跟著移動,也不會通知輔助技術內容已變。

改良版:不寫死數量、支援鍵盤

<style>
.tab-panel[hidden] { display: none; }
.tab-list { display: flex; gap: 4px; border-bottom: 1px solid #ccc; }
.tab-list button {
    padding: 6px 14px; border: 1px solid #ccc; border-bottom: none;
    background: #f0f0f0; cursor: pointer;
}
.tab-list button[aria-selected="true"] { background: #fff; font-weight: bold; }
</style>

<div class="tabs">
  <div class="tab-list" role="tablist">
    <button role="tab" aria-selected="true"  aria-controls="panel-0">內容一</button>
    <button role="tab" aria-selected="false" aria-controls="panel-1">內容二</button>
    <button role="tab" aria-selected="false" aria-controls="panel-2">內容三</button>
  </div>

  <div id="panel-0" class="tab-panel" role="tabpanel">內容部分第一區</div>
  <div id="panel-1" class="tab-panel" role="tabpanel" hidden>內容部分第二區</div>
  <div id="panel-2" class="tab-panel" role="tabpanel" hidden>內容部分第三區</div>
</div>

<script>
(function () {
    var tabs = Array.prototype.slice.call(document.querySelectorAll('.tab-list [role="tab"]'));

    function activate(index) {
        tabs.forEach(function (tab, i) {
            var selected = (i === index);
            tab.setAttribute('aria-selected', String(selected));
            document.getElementById(tab.getAttribute('aria-controls')).hidden = !selected;
        });
    }

    tabs.forEach(function (tab, i) {
        tab.addEventListener('click', function () { activate(i); });
        // 左右鍵在標籤間移動,符合 ARIA 標籤頁的慣例
        tab.addEventListener('keydown', function (e) {
            var next = null;
            if (e.key === 'ArrowRight') next = (i + 1) % tabs.length;
            if (e.key === 'ArrowLeft')  next = (i - 1 + tabs.length) % tabs.length;
            if (next !== null) {
                e.preventDefault();
                activate(next);
                tabs[next].focus();
            }
        });
    });
})();
</script>

這一版的差異:用 querySelectorAll 自動取得所有標籤,數量不必寫死;用 hidden 屬性取代 style.display,語意更清楚;加上 role="tablist"、role="tab"、aria-selected、aria-controls 這套 ARIA 標記,螢幕閱讀器就能正確朗讀「這是哪一個標籤、目前選了哪一個」;並支援左右方向鍵切換。

如果只是想快速做出來,HTML 原生已有現成方案——<details> 搭配 <summary> 可做手風琴;而新興的 popover API 也能處理這類「切換可見性」的需求,不必寫 JavaScript。若專案已有前端框架,Radix UI、Headless UI 等無樣式元件庫都提供了完整的無障礙標籤頁實作。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved