<分区>
标签 javascript html css
请看下图:
我想创建一个这样的菜单,但我不知道如何开始。有什么想法吗?
最佳答案
其实很简单。它包含在递归节点列表中。
您可以通过同时使用 ul
、li
和 a
来实现:
<ul>
<li>
<a>Text here</a>
<!-- repeat -->
</li>
</ul>
执行该行为也非常简单。您必须查看 a
元素是否有 nextElementSibling
,如果有,那是因为当前节点有子节点。
看看下面我创建的示例:
(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);
}
}
});
})();
.hidden {
display: none;
}
<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>
关于javascript - 如何在 HTML/Javascript 中创建递归菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32919569/