当前位置:首页 > JavaScript

js实现tree实现树菜单

2026-04-07 06:20:36JavaScript

实现树形菜单的JavaScript方法

数据结构设计

使用对象数组表示树节点,每个节点包含idlabelchildren等属性:

const treeData = [
  {
    id: 1,
    label: 'Parent 1',
    children: [
      {
        id: 2,
        label: 'Child 1',
        children: []
      }
    ]
  }
]

递归渲染方法

通过递归函数遍历树结构并生成DOM元素:

function renderTree(node, parentElement) {
  const li = document.createElement('li');
  li.textContent = node.label;

  if (node.children && node.children.length > 0) {
    const ul = document.createElement('ul');
    node.children.forEach(child => renderTree(child, ul));
    li.appendChild(ul);
  }

  parentElement.appendChild(li);
}

事件处理

添加展开/折叠功能的事件监听:

document.querySelectorAll('li').forEach(li => {
  li.addEventListener('click', (e) => {
    e.stopPropagation();
    const ul = li.querySelector('ul');
    if (ul) ul.style.display = ul.style.display === 'none' ? 'block' : 'none';
  });
});

完整组件实现

结合上述方法的完整树组件示例:

class TreeMenu {
  constructor(containerId, data) {
    this.container = document.getElementById(containerId);
    this.data = data;
    this.render();
  }

  renderNode(node) {
    const nodeElement = document.createElement('div');
    nodeElement.className = 'tree-node';
    nodeElement.innerHTML = `
      <div class="node-label">${node.label}</div>
      ${node.children?.length ? `<div class="children"></div>` : ''}
    `;

    if (node.children) {
      const childrenContainer = nodeElement.querySelector('.children');
      node.children.forEach(child => {
        childrenContainer.appendChild(this.renderNode(child));
      });
    }

    return nodeElement;
  }

  render() {
    this.data.forEach(rootNode => {
      this.container.appendChild(this.renderNode(rootNode));
    });
  }
}

CSS样式建议

为树形菜单添加基础样式:

.tree-node {
  margin-left: 20px;
}
.node-label {
  cursor: pointer;
  padding: 5px;
}
.node-label:hover {
  background-color: #f0f0f0;
}
.children {
  display: none;
}
.children.show {
  display: block;
}

动态加载优化

实现按需加载子节点的优化方案:

function lazyLoadChildren(node, callback) {
  if (!node.loaded && node.hasChildren) {
    fetch(`/api/nodes/${node.id}`)
      .then(res => res.json())
      .then(children => {
        node.children = children;
        node.loaded = true;
        callback();
      });
  }
}

第三方库方案

使用现有库快速实现(如zTree):

js实现tree实现树菜单

// 引入zTree库后
const setting = {
  data: { simpleData: { enable: true } }
};
const zNodes = [
  { id:1, pId:0, name:"父节点" },
  { id:11, pId:1, name:"子节点" }
];
$.fn.zTree.init($("#tree"), setting, zNodes);

标签: 菜单js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

vue实现折叠菜单

vue实现折叠菜单

实现折叠菜单的基本思路 在Vue中实现折叠菜单通常涉及使用组件化开发,结合状态管理控制菜单的展开与折叠。核心是通过v-show或v-if动态切换子菜单的显示状态,并通过事件触发(如点击)改变状态。…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…

js进度条实现

js进度条实现

使用HTML和CSS创建基础结构 在HTML中创建一个容器元素用于显示进度条,通常使用<div>元素。CSS用于设置进度条的样式,包括宽度、高度、颜色和圆角等属性。 <div cl…