萬盛學電腦網

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

JavaScript 實現滑鼠感應下滑顯示/隱藏選單

效果描述

頁面左上角固定一個標籤,當滑鼠移入該區域時,選單面板平滑下滑展開;滑鼠移出後,面板自動上滑收回。適用於側邊導航、快捷工具列等場景。

核心邏輯

  • 使用 position: absolute 或 fixed 定位選單容器,初始 top 設為負值(隱藏在可視區外)。
  • 監聽 mouseover/mouseout(或 mouseenter/mouseleave)事件。
  • 以 setInterval 或 requestAnimationFrame 漸進式修改 top / transform: translateY() 實現動畫。
  • 利用 clearTimeout 管理動畫佇列,避免重複觸發造成抖動。

現代化重構範例(ES6 + CSS Transition)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>滑鼠感應滑出選單</title>
  <style>
    #slideMenu {
      position: fixed;
      top: 0;
      left: 0;
      width: 260px;
      background: #2c3e50;
      color: #ecf0f1;
      transform: translateY(-100%); /* 初始隱藏 */
      transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);
      z-index: 1000;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
    #slideMenu.show { transform: translateY(0); }
    .menu-tab {
      display: inline-block;
      padding: 8px 16px;
      background: #e74c3c;
      color: #fff;
      cursor: pointer;
      user-select: none;
    }
    .menu-content { padding: 16px; }
    .menu-content a {
      display: block;
      color: #bdc3c7;
      text-decoration: none;
      padding: 6px 0;
      transition: color 0.2s;
    }
    .menu-content a:hover { color: #fff; }
  </style>
</head>
<body>
  <div id="slideMenu">
    <div class="menu-tab">☰ 選單</div>
    <div class="menu-content">
      <a href="#home">首頁</a>
      <a href="#products">產品介紹</a>
      <a href="#about">關於我們</a>
      <a href="#contact">聯絡我們</a>
    </div>
  </div>

  <script>
    (function() {
      var menu = document.getElementById('slideMenu');
      var tab = menu.querySelector('.menu-tab');
      var hideTimer;

      function show() {
        clearTimeout(hideTimer);
        menu.classList.add('show');
      }
      function hide() {
        hideTimer = setTimeout(function() {
          menu.classList.remove('show');
        }, 150); // 稍微延遲,避免游標瞬間離開誤觸發
      }

      // 綁定在整個選單容器上,包含標籤與內容區
      menu.addEventListener('mouseenter', show);
      menu.addEventListener('mouseleave', hide);

      // 鍵盤無障礙:Tab 聚焦時也展開
      tab.addEventListener('focus', show);
      menu.addEventListener('focusout', function(e) {
        if (!menu.contains(e.relatedTarget)) hide();
      });
    })();
  </script>
</body>
</html>

關鍵改進點

  1. CSS Transition 取代 JS 逐幀動畫:瀏覽器原生動畫效能更高、程式碼更簡潔。
  2. 使用 transform: translateY():不觸發佈局重排,比操作 top 流暢。
  3. 事件委派與 mouseenter/leave:不冒泡,避免子元素觸發多次進出。
  4. 無障礙支援:鍵盤 Tab 可聚焦標籤並展開,符合 WCAG 基礎要求。
  5. 防抖動延遲:mouseleave 加入 150ms 延遲,避免游標快速劃過導致選單閃爍。

舊版 IE 相容說明(原始碼邏輯)

原文採用 document.all 判斷 IE4+、document.layers 判斷 Netscape 4,並分別操作 pixelTop(IE)或 top(NS4)配合 setTimeout(fn, 1) 實現逐像素動畫。此寫法已無現代實務價值,僅供歷史參考。若必須支援 IE8 以下,可保留 JS 動畫邏輯並加入 requestAnimationFrame polyfill。

總結

滑鼠感應滑出選單是經典 UI 模式。現代開發應優先採用 CSS 動畫 + 類別切換,搭配少量 JS 控制狀態,兼顧效能、維護性與無障礙。若專案需支援極舊瀏覽器,可針對性提供降級方案,而非全專案採用舊式逐幀動畫。

copyright © 萬盛學電腦網 all rights reserved