树形菜单是一种常见的用户界面元素,用于展示层次结构的数据。它通常以树状图的形式展示,每个节点可以有多个子节点。默认展开指的是页面加载时,某些节点已经处于展开状态,而不是折叠状态。
以下是一个简单的JavaScript示例,展示如何实现树形菜单的默认展开:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tree Menu Example</title>
<style>
.tree-node {
margin-left: 20px;
}
.tree-toggle {
cursor: pointer;
}
</style>
</head>
<body>
<div id="treeMenu">
<div class="tree-node">
<span class="tree-toggle">+</span> Node 1
<div class="tree-children" style="display: none;">
<div class="tree-node">Node 1.1</div>
<div class="tree-node">Node 1.2</div>
</div>
</div>
<div class="tree-node">
<span class="tree-toggle">+</span> Node 2
<div class="tree-children" style="display: none;">
<div class="tree-node">Node 2.1</div>
<div class="tree-node">Node 2.2</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const nodesToExpand = ['Node 1']; // 定义需要默认展开的节点
nodesToExpand.forEach(nodeName => {
const node = document.querySelector(`.tree-node:contains(${nodeName})`);
if (node) {
node.querySelector('.tree-toggle').textContent = '-';
node.querySelector('.tree-children').style.display = 'block';
}
});
document.querySelectorAll('.tree-toggle').forEach(toggle => {
toggle.addEventListener('click', function() {
const children = this.nextElementSibling;
if (children.style.display === 'none') {
children.style.display = 'block';
this.textContent = '-';
} else {
children.style.display = 'none';
this.textContent = '+';
}
});
});
});
// 扩展String原型以支持:contains选择器
String.prototype.contains = function(str) {
return this.indexOf(str) !== -1;
};
Element.prototype.contains = function(el) {
return this === el || (this.contains && this.contains(el));
};
Element.prototype.querySelector = function(selector) {
if (typeof selector === 'string') {
const match = selector.match(/:(\w+)(?:\((.*?)\))?/);
if (match) {
const pseudo = match[1];
const value = match[2];
if (pseudo === 'contains') {
return Array.from(this.children).find(el => el.textContent.contains(value));
}
}
}
return this.firstChild;
};
</script>
</body>
</html>
通过以上方法,可以有效实现树形菜单的默认展开功能,并解决常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云