如何在HTML / Javascript中创建递归菜单?

时间:2015-10-03 06:18:43

标签: javascript html css

看看下图:

enter image description here

我想创建一个这样的菜单,但我不知道如何开始。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

事实上,它非常简单。它包含一个递归节点列表。

您可以同时使用ullia来实现这一目标:

<ul>
  <li>
    <a>Text here</a>
    <!-- repeat -->
  </li>
</ul>

为了表现这种行为,它也非常简单。您必须查看a元素是否有nextElementSibling,如果有{1},则它是因为当前节点有子节点。

看一下我创建的下面的例子:

&#13;
&#13;
(function() {
  var tree = document.getElementById('tree');

  /* firstly, we hide all the child items */
  [].forEach.call(tree.querySelectorAll('ul li a'), function(el, i) {
    if (el.nextElementSibling)
      el.nextElementSibling.classList.add('hidden');
  });

  /* here we make a event delegation, we add an event handler to the hole tree */
  tree.addEventListener('click', function(e) {
    var el = e.target;

    /* if the element clicked is an anchor, it's because it's a node/leaf */
    if (el.tagName === 'A') {
      e.preventDefault();
      
      /* if it has a nextElementSibling, it's because it has children, so it's a node */
      if (el.nextElementSibling) {
        /* we toggle the visibility of the child */
        el.nextElementSibling.classList.toggle('hidden');
      } else {
        // do something with the final child (leaf)
        console.log(el.textContent);
      }
    }
  });
})();
&#13;
.hidden {
  display: none;
}
&#13;
<div id="tree">
  <ul>
    <li>
      <a>Father</a>
      <ul>
        <li>
          <a>Son</a>
        </li>
      </ul>
    </li>
    <li>
      <a>Grandfather</a>
      <ul>
        <li>
          <a>Father</a>
          <ul>
            <li>
              <a>Son</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>
    <li>
      <a>Father</a>
      <ul>
        <li>
          <a>Son</a>
        </li>
      </ul>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;