JavaScript 树形下拉菜单是一种常见的用户界面元素,用于展示层次结构的数据,并允许用户通过点击来展开或折叠子菜单。下面是一个简单的树形下拉菜单的实现示例:
以下是一个简单的静态树形下拉菜单的HTML和JavaScript代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tree Dropdown Menu</title>
<style>
.tree, .tree ul {
margin:0;
padding:0;
list-style:none;
}
.tree ul {
margin-left:1em;
position:relative;
}
.tree ul ul {
margin-left:.5em;
}
.tree li {
margin:0;
padding:0 1em;
line-height:2em;
color:#369;
font-weight:bold;
position:relative;
}
.tree ul li:before {
content:"";
display:block;
width:0;
height:0;
border-top:1px solid #369;
position:absolute;
top:1em;
left:0;
}
.tree li a {
text-decoration:none;
color:#369;
}
</style>
</head>
<body>
<ul class="tree">
<li><a href="#">Parent Node 1</a>
<ul>
<li><a href="#">Child Node 1.1</a></li>
<li><a href="#">Child Node 1.2</a>
<ul>
<li><a href="#">Grandchild Node 1.2.1</a></li>
<li><a href="#">Grandchild Node 1.2.2</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Parent Node 2</a></li>
</ul>
<script>
// JavaScript to handle tree toggle (optional)
document.querySelectorAll('.tree > li').forEach(function(li) {
li.addEventListener('click', function(e) {
e.stopPropagation();
var ul = this.querySelector('ul');
if (ul) {
ul.style.display = ul.style.display === 'none' ? 'block' : 'none';
}
});
});
</script>
</body>
</html>
如果子菜单不展开或折叠,可以检查JavaScript代码是否正确执行:
// 确保事件监听器正确绑定
document.querySelectorAll('.tree > li').forEach(function(li) {
li.addEventListener('click', function(e) {
e.stopPropagation();
var ul = this.querySelector('ul');
if (ul) {
ul.style.display = ul.style.display === 'none' ? 'block' : 'none';
}
});
});
确保CSS样式没有被覆盖:
/* 确保树形菜单的样式优先级足够高 */
.tree ul {
display: none; /* 默认隐藏子菜单 */
}
通过以上代码和解释,你应该能够创建一个基本的树形下拉菜单,并理解其工作原理和可能的解决方案。
领取专属 10元无门槛券
手把手带您无忧上云