萬盛學電腦網

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

JSON 驅動的無限級遞迴折疊菜單:數據結構設計、渲染算法與交互封裝

後端返回樹形 JSON,前端遞迴渲染無限級折疊菜單。本文涵蓋數據結構定義、遞迴渲染函數、展開/收起狀態管理、鍵盤無障礙、懶加載子節點、虛擬滾動大數據優化。

標準樹形數據結構

interface MenuNode {
  id: string | number;
  label: string;
  url?: string;           // 葉子節點導航鏈接
  icon?: string;          // 圖標類名
  children?: MenuNode[];  // 子節點,無則為葉子
  disabled?: boolean;
}

// 示例數據
const menuData = [
  { id: 1, label: '系統管理', children: [
    { id: 11, label: '用戶管理', url: '/users' },
    { id: 12, label: '角色權限', children: [
      { id: 121, label: '角色列表', url: '/roles' },
      { id: 122, label: '權限分配', url: '/permissions' }
    ]}
  ]},
  { id: 2, label: '內容管理', url: '/content' }
];

遞迴渲染組件

function renderMenu(nodes, parentId = 'menu-root') {
  const ul = document.createElement('ul');
  ul.className = 'menu';
  ul.role = 'tree';
  ul.setAttribute('aria-labelledby', parentId);

  nodes.forEach(node => {
    const li = document.createElement('li');
    li.className = 'menu-item';
    li.dataset.id = node.id;

    if (node.children?.length) {
      // 父節點:按鈕觸發展開
      const btn = document.createElement('button');
      btn.className = 'menu-trigger';
      btn.setAttribute('aria-expanded', 'false');
      btn.innerHTML = `▶${escapeHtml(node.label)}`;
      li.appendChild(btn);

      const subUl = renderMenu(node.children, `menu-${node.id}`);
      subUl.hidden = true;
      subUl.id = `menu-${node.id}`;
      li.appendChild(subUl);

      btn.addEventListener('click', () => {
        const expanded = btn.getAttribute('aria-expanded') === 'true';
        btn.setAttribute('aria-expanded', !expanded);
        subUl.hidden = expanded;
        btn.querySelector('.icon').style.transform = expanded ? '' : 'rotate(90deg)';
      });
    } else {
      // 葉子節點:鏈接
      const a = document.createElement('a');
      a.href = node.url || '#';
      a.textContent = node.label;
      if (node.disabled) { a.classList.add('disabled'); a.removeAttribute('href'); }
      li.appendChild(a);
    }
    ul.appendChild(li);
  });
  return ul;
}

document.getElementById('sidebar').appendChild(renderMenu(menuData));

CSS 關鍵樣式

.menu { list-style: none; padding: 0; margin: 0; }
.menu-item { position: relative; }
.menu-trigger { display: flex; align-items: center; width: 100%; padding: 8px 12px; background: none; border: none; text-align: left; cursor: pointer; }
.menu-trigger[aria-expanded="true"] .icon { transform: rotate(90deg); }
.menu-item > ul { padding-left: 24px; }
.menu a { display: block; padding: 6px 12px; color: #333; text-decoration: none; }
.menu a:hover { background: #f0f0f0; }

進階功能

懶加載子節點

btn.addEventListener('click', async () => {
  if (subUl.dataset.loaded) return toggle();
  const res = await fetch(`/api/menu/${node.id}/children`);
  const children = await res.json();
  subUl.appendChild(renderMenu(children));
  subUl.dataset.loaded = 'true';
  toggle();
});

狀態持久化

// 展開狀態存 localStorage,頁面載入時恢復
const saveState = () => { /* 遍歷收集 aria-expanded=true 的 id */ };
const restoreState = () => { /* 讀取 localStorage 觸發 click */ };

虛擬滾動(大數據)

節點 > 500 時,使用 react-window、vue-virtual-scroller 或原生 IntersectionObserver 實現可視區渲染。

copyright © 萬盛學電腦網 all rights reserved