DIV CSS 佈局教程網

用 jQuery + div + CSS 實作無限層級的級聯樹
編輯:JQuery特效代碼     

組織架構、商品分類、地區選單、權限樹——只要資料有父子關係,就需要一顆樹。傳統做法是用 table 拼湊,或用 setTimeout 延後載入子節點。本文示範如何以純 div 與 CSS 建立巢狀結構,再用 jQuery 處理展開收合,讓同一套程式碼支援任意深度。

一、資料結構決定一切

常見兩種表示法:扁平清單(每筆有 id 與 parentId)或 Already 巢狀(每個節點帶 children 陣列)。後端多回傳扁平資料,前端再組樹:

const flat = [
  { id: 1, pid: 0, name: '台灣' },
  { id: 2, pid: 1, name: '台北市' },
  { id: 3, pid: 2, name: '大安區' },
  { id: 4, pid: 1, name: '新竹縣' }
];

function buildTree(list, pid = 0) {
  return list
    .filter(item => item.pid === pid)
    .map(item => ({ ...item, children: buildTree(list, item.id) }));
}

二、HTML 結構與 CSS

用巢狀 div 加上縮排線條,比 ul/li 更容易完全掌控樣式:

<style>
.tree, .tree .children { list-style: none; }
.tree-node { margin-left: 14px; position: relative; }
.tree-node::before {          /* 階層連接線 */
  content: ''; position: absolute; left: -10px; top: 0;
  bottom: 0; width: 1px; background: #dcdfe6;
}
.tree-label {
  display: flex; align-items: center; gap: 6px;
  padding: 4px 8px; cursor: pointer; border-radius: 4px;
}
.tree-label:hover { background: #f2f6fc; }
.tree-node.is-active > .tree-label {
  background: #409eff; color: #fff;
}
.children { display: none; }
.tree-node.is-open > .children { display: block; }
.toggle { width: 12px; text-align: center; user-select: none; }
</style>

<div class="tree" id="tree"></div>

三、遞迴渲染

function render(nodes, container) {
  const frag = document.createDocumentFragment();

  nodes.forEach(node => {
    const hasChild = node.children && node.children.length;
    const li = document.createElement('div');
    li.className = 'tree-node';
    li.dataset.id = node.id;

    li.innerHTML =
      '<div class="tree-label">' +
        '<span class="toggle">' + (hasChild ? '▸' : '') + '</span>' +
        '<span class="name">' + escapeHtml(node.name) + '</span>' +
      '</div>';

    if (hasChild) {
      const box = document.createElement('div');
      box.className = 'children';
      li.appendChild(box);
      render(node.children, box);
    }
    frag.appendChild(li);
  });

  container.appendChild(frag);
}

render(buildTree(flat), document.getElementById('tree'));

四、展開收合:用事件委派

動態產生的節點無法用一般方式直接綁定事件,改用事件委派掛在容器上,一次搞定所有層級:

$('#tree').on('click', '.toggle', function (e) {
  e.stopPropagation();
  const node = $(this).closest('.tree-node');
  node.toggleClass('is-open');
  $(this).text(node.hasClass('is-open') ? '▾' : '▸');
});

$('#tree').on('click', '.name', function () {
  $('#tree .tree-node').removeClass('is-active');
  $(this).closest('.tree-node').addClass('is-active');
  console.log('選取節點 id =', $(this).closest('.tree-node').data('id'));
});

// 全部展開 / 收起
$('#expandAll').on('click', () => {
  $('.tree-node').addClass('is-open').children('.toggle').text('▾');
});
$('#collapseAll').on('click', () => {
  $('.tree-node').removeClass('is-open').children('.toggle').text('▸');
});

五、進階需求怎麼做

  • 搜尋定位:比對名稱後,對命中的節點與其所有祖先加上 is-open,即可自動展開路徑並捲動到該處。
  • 虛擬滾動:節點數破千時,一次渲染全部 DOM 會明顯卡頓,此時應改為只渲染可視區域,或改用專門的虛擬列表元件。
  • 鍵盤操作:為 .tree-label 加上 tabindex="0" 與 role="treeitem"、aria-expanded,並處理上下鍵移動、左右鍵展開收合,讓鍵盤與螢幕閱讀器使用者也能操作。
  • 避免 innerHTML 拼接使用者資料:節點名稱來自後端時必須先做轉義,否則等於開了一個 XSS 入口。
  • 效能:CSS 用 display 切換即可,不要用 jQuery animate 逐格改 height;大量節點的收合動畫反而會讓人覺得卡。

結語

「無限層級」的重點不在寫出多深的迴圈,而在三件事:資料要先正化成樹、渲染要遞迴、事件要委派。這三點做對,深度就不再是你需要擔心的問題。

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