萬盛學電腦網

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

JavaScript 實作動態省市縱向下拉選單(滑鼠懸停展開子選單)

本文示範以原生 DOM 動態建立「省市縱向導航選單」:左側省份列表,滑鼠懸停省份時右側彈出對應城市子選單。資料結構為省份-城市映射物件,支援動態寬度自適應、CSS 類名切換顯示/隱藏,適合側邊欄導航、地址選擇器等場景。

資料結構:省市映射物件

var provs = {
    "江西省": ["南昌市", "景德鎮", "九江", "鷹潭", "萍鄉", "新馀", "贛州", "吉安", "宜春", "撫州", "上饒"],
    "福建省": ["福州", "廈門", "莆田", "三明", "泉州", "漳州", "南平", "龍巖", "寧德"],
    "河北省": ["石家莊", "邯鄲", "邢台", "保定", "張家口", "承德", "廊坊", "唐山", "秦皇島", "滄州", "衡水"],
    "四川省": ["成都市", "自貢市", "攀枝花市", "瀘州市", "德陽市", "綿陽市", "廣元市", "遂寧市", "內江市", "樂山市", "南充市", "眉山市", "宜賓市", "廣安市", "達州市", "雅安市", "巴中市", "資陽市", "阿壩藏族羌族自治州", "甘孜藏族自治州", "涼山彝族自治州"],
    // ... 更多省份
};

動態建立選單結構

function loadData() {
    var provUL = document.getElementById("prov");
    var nIndex = 0;
    
    for (var key in provs) {
        // 建立省份 
  • var provLi = document.createElement("li"); provLi.id = "provLI" + nIndex; provLi.innerHTML = "<a href='#'>" + key + "</a>"; provUL.appendChild(provLi); // 建立城市子選單
      var cities = provs[key]; if (cities.length > 0) { var cityUL = document.createElement("ul"); var maxLength = 0; for (var i = 0; i < cities.length; i++) { var cityName = cities[i]; // 計算最長城市名,用於自適應寬度 if (cityName.length > maxLength) maxLength = cityName.length; var cityLI = document.createElement("li"); cityLI.id = "cityLI" + i; cityLI.innerHTML = "<a href='#'>" + cityName + "</a>"; cityUL.appendChild(cityLI); } // 設定子選單寬度:中文約 20px/字,最小 100px var width = (maxLength <= 6) ? "100px" : (maxLength * 20 + "px"); cityUL.style.width = width; provLi.appendChild(cityUL); // 掛載到省份 li 內部 } nIndex++; } }
  • 滑鼠互動:CSS 類名切換顯示/隱藏

    function iniEvent() {
        var provUL = document.getElementById("prov");
        if (!provUL) return;
        
        var allLi = provUL.getElementsByTagName("li");
        for (var i = 0; i < allLi.length; i++) {
            var node = allLi[i];
            
            node.onmouseover = function() {
                this.className = "current"; // 觸發 CSS 顯示子選單
            };
            
            node.onmouseout = function() {
                this.className = this.className.replace("current", ""); // 移除類名隱藏
            };
        }
    }

    CSS 關鍵樣式

    <style>
    #menu { width: 100px; border: 1px solid #CCC; border-bottom: none; }
    #menu ul { list-style: none; margin: 0; padding: 0; }
    #menu ul li { 
        background: #eee; 
        padding: 0 8px; 
        height: 26px; 
        line-height: 26px; 
        border-bottom: 1px solid #CCC; 
        position: relative; /* 關鍵:子選單定位基準 */
    }
    #menu ul li ul { 
        display: none; 
        position: absolute; 
        left: 100px; /* 緊貼父選單右側 */
        top: 0; 
        width: 100px; 
        border: 1px solid #ccc; 
        border-bottom: none; 
    }
    #menu ul li.current ul { display: block; } /* 懸停顯示 */
    #menu ul li ul li { text-align: center; } /* 城市文字置中 */
    a { color: #000; text-decoration: none; }
    a:hover { color: #F00; }
    </style>

    HTML 結構

    <div id="menu">
        <ul id="prov"></ul> <!-- 省份由 JS 動態填入 -->
    </div>
    <script> window.onload = function() { loadData(); iniEvent(); }; </script>

    關鍵實作細節

    1. 巢狀結構:城市 <ul> 掛載在省份 <li> 內部,利用 position: relative + absolute 定位
    2. 寬度自適應:遍歷城市名計算最大字元數,動態設定 cityUL.style.width
    3. CSS 狀態控制:.current 類名控制子選單 display: block/none,無需 JS 直接操作 style
    4. 事件綁定:onmouseover/onmouseout 切換類名,簡單高效

    現代化改進方向

    1. 鍵盤無障礙支援

    // 新增鍵盤導航
    provLi.setAttribute('tabindex', '0'); // 可聚焦
    provLi.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            e.target.classList.toggle('current');
        }
        if (e.key === 'Escape') e.target.classList.remove('current');
    });

    2. 延遲隱藏(防止誤觸)

    let hideTimer;
    node.onmouseout = function() {
        hideTimer = setTimeout(() => this.className = this.className.replace("current", ""), 200);
    };
    node.onmouseover = function() {
        clearTimeout(hideTimer);
        this.className = "current";
    };

    3. 觸控裝置支援

    node.addEventListener('touchstart', e => {
        e.preventDefault(); // 防止觸發 click
        this.classList.toggle('current');
    }, { passive: false });

    4. 資料外部化 + 現代模組

    // provinces.js
    export const provinces = { /* ... */ };
    
    // menu.js
    import { provinces } from './provinces.js';
    
    class VerticalCascader {
        constructor(containerId) {
            this.root = document.getElementById(containerId);
            this.render();
            this.bindEvents();
        }
        // ... 封裝 render、bindEvents、鍵盤/觸控支援
    }

    總結

    縱向省市選單核心在於:巢狀 DOM 結構 + CSS 絕對定位 + 類名狀態控制。原始範例展示了 DOM 動態建立的經典模式,現代開發建議採用「資料驅動視圖」模式,搭配 CSS Transition 動畫、無障礙屬性、觸控支援,打造生產級導航元件。

    copyright © 萬盛學電腦網 all rights reserved