DIV CSS 佈局教程網

選項卡進階:加上自動輪播與 hover 暫停
編輯:JavaScript綜合知識     

在基本選項卡上加「自動切換」,看似只是多幾行,實際上會碰觸到計時器管理這個容易出錯的領域。本文示範的版本把自動播放與手動點擊協調起來。

設計思路

用一個數字 num 當作「目前在第幾個」的指標,每 1000 毫秒 num++ 並呼叫切換函式;超過長度就歸零。滑鼠移入時 clearInterval 暫停,移出時重新啟動。

重點是:切換的動作要抽成獨立函式,讓計時器與點擊事件都能呼叫同一份邏輯,避免兩處各寫一遍導致行為不一致。

結構與樣式

.wrap { width:500px; margin:20px auto; }
.hide { display:none; }
#tab_t { height:25px; border-bottom:1px solid #ccc; }
#tab_t li { float:left; width:80px; height:24px; line-height:24px; margin:0 4px;
            text-align:center; border:1px solid #ccc; border-bottom:none;
            background:#f5f5f5; cursor:pointer; }
#tab_t .act { position:relative; height:25px; margin-bottom:-1px; background:#fff; }
#tab_c { border:1px solid #ccc; border-top:none; padding:20px; }
<div class="wrap">
  <ul id="tab_t">
    <li class="act">選擇1</li><li>選擇2</li><li>選擇3</li><li>選擇4</li>
  </ul>
  <div id="tab_c">
    <div>內容1</div>
    <div class="hide">內容2</div>
    <div class="hide">內容3</div>
    <div class="hide">內容4</div>
  </div>
</div>

程式

window.onload = function () {
  tab("tab_t", "li", "tab_c", "div", "onmouseover");

  function tab(tab_t_id, tab_t_tag, tab_c_id, tab_c_tag, evt) {
    var tab_t    = document.getElementById(tab_t_id);
    var tab_t_li = tab_t.getElementsByTagName(tab_t_tag);
    var tab_c    = document.getElementById(tab_c_id);
    var tab_c_li = tab_c.getElementsByTagName(tab_c_tag);
    var len = tab_t_li.length;
    var timer = null;
    var num = 0;

    for (var i = 0; i < len; i++) {
      tab_t_li[i].index = i;

      tab_t_li[i][evt] = function () {
        clearInterval(timer);        // 手動操作時先停掉自動播放
        num = this.index;
        tab_change();
      };

      tab_t_li[i].onmouseout = function () {
        autoplay();                  // 離開後恢復
      };
    }

    function tab_change() {
      for (var i = 0; i < len; i++) {
        tab_t_li[i].className = '';
        tab_c_li[i].className = 'hide';
      }
      tab_t_li[num].className = 'act';
      tab_c_li[num].className = '';
    }

    function autoplay() {
      clearInterval(timer);          // 先清掉舊的,避免疊加多顆計時器
      timer = setInterval(function () {
        num++;
        if (num >= len) num = 0;
        tab_change();
      }, 1000);
    }

    autoplay();
  }
};

autoplay() 開頭那個 clearInterval(timer) 是防禦性的關鍵。少了它,滑鼠每移出一次就多一顆計時器在跑,畫面會愈切愈快,而且再也停不下來。這是計時器類功能最典型的 bug。

這個版本還缺什麼

滑鼠移出才恢復,鍵盤使用者沒有對應行為。應該在 focusin 時暫停、focusout 時恢復,讓 Tab 鍵操作的人也能安心閱讀。

自動輪播必須提供暫停鈕。這是 WCAG 2.2.2 的明確要求:任何自動更新且持續超過五秒的資訊,都要有暫停、停止或隱藏機制。同時也該在 prefers-reduced-motion 時預設關閉自動播放。

1 秒太快了。輪播每張至少留 4–6 秒,一般使用者才讀得完。1000 毫秒只適合純視覺展示。

切換沒有動畫。加上 transition: opacity .3s 並在切換時調整 class,比硬跳舒服很多。

計時器沒有在頁面隱藏時暫停。加上 document.visibilitychange 監聽,分頁切到背景時停止,回來再恢復,省電也避免回來時狀態混亂。

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