Skip to content

Instantly share code, notes, and snippets.

@tiam-bloom
Created February 25, 2023 04:47
Show Gist options
  • Save tiam-bloom/5ddac02cc87a2bfaac607ef2cce16404 to your computer and use it in GitHub Desktop.
Save tiam-bloom/5ddac02cc87a2bfaac607ef2cce16404 to your computer and use it in GitHub Desktop.
可折叠树形菜单
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<style>
li:hover {
cursor: pointer;
}
.tree span:hover {
font-weight: bold;
}
</style>
<body>
<ul class="tree" id="tree">
<li>
Animals
<ul>
<li>
Mammals
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
</ul>
</li>
<li>
Other
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
</ul>
</li>
</ul>
</li>
<li>
Fishes
<ul>
<li>
Aquarium
<ul>
<li>Guppy</li>
<li>Angelfish</li>
</ul>
</li>
<li>
Sea
<ul>
<li>Sea trout</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
// 为每个菜单项标题 添加一个span元素, 方便添加样式
for (let li of tree.querySelectorAll("li")) {
let span = document.createElement("span");
li.prepend(span);
span.append(span.nextSibling); // move the text node into span
}
tree.onclick = function (e) {
// 获取点击的子节点ul, 因为添加了一个span元素, 所以要向上查找一层
let child = e.target.parentNode.querySelector("ul");
if (child != null) child.hidden = !child.hidden;
};
</script>
</body>
</html>
@tiam-bloom
Copy link
Author

不添加span也可实现, span只是为了样式

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment