Created
February 25, 2023 04:47
-
-
Save tiam-bloom/5ddac02cc87a2bfaac607ef2cce16404 to your computer and use it in GitHub Desktop.
可折叠树形菜单
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
不添加span也可实现, span只是为了样式