使用原生js读取树形结构对象构筑多级结构菜单

来源:互联网 发布:淘宝特种经营许可申请 编辑:程序博客网 时间:2024/06/01 07:27

最近新项目的需求给我出了个难题,让我读取树形结构的对象来构筑悬浮响应式的多级菜单,因为用的是ng2框架,本来打算使用ng2-tree作为插件,可是这个插件对外开放的接口太少了,连样式接口都没有,只能用默认样式,唯有样式客户决不妥协,无奈之下只能想到用原生js的dom操作来实现。以下是代码

js部分,主要用递归方法构筑树形结构菜单

<script>
//树形结构每个节点结构基本相同
var data = {
id: "01",
value: "维度管理",
children: [
{
id: "11",
value: "岗位",
children: []
},
{
id: "12",
value: "部门",
children: [
{
id: "121",
value: "信息部",
children: []
},
{
id: "122",
value: "营运部",
children: [
{
id: "1221",
value: "营运条例",
children: []
},
{
id: "1222",
value: "运营管理",
children: []
},
{
id: "1223",
value: "运营规范",
children: []
}
]
},
{
id: "123",
value: "质量部",
children: []
},
{
id: "124",
value: "创新部",
children: []
},
{
id: "125",
value: "销售部",
children: []
}
]
},
{
id: "13",
value: "集团",
children: []
},
{
id: "14",
value: "分公司",
children: []
}
]
};
//调用方法
valueSet(data,"dimension-tree");
//data可替换为动态获取的数据
//例如
// private loadDimension(url: string) {
// return this.httpServiceService.getHttp(url).subscribe(
// res => {
// this.valueSet(res, "dimension-tree");
// },
// error => {
// console.log('错误', error);
// }
// );
// }
function valueSet(dataObject,id) {
if (dataObject.children.length >0) {
for (iindataObject.children) {
this.DomEdt(id,dataObject.children[i]);
this.valueSet(dataObject.children[i],dataObject.children[i].id);
}
}
}
//DOM操作
function DomEdt(id,obj) {
var li =document.createElement('li');
document.getElementById(id).appendChild(li);
var a =document.createElement('a');
a.className ="dimensionA";
a.textContent =obj.value;
a.onclick =this.Onclick;
li.appendChild(a);
li.className ="dimensionLi";
var ul =document.createElement('ul');
li.appendChild(ul);
ul.id =obj.id;
ul.className ="dimensionUl";
// ul.style.cssText = 'display:none';
}
//节点绑定事件,可获取节点相关内容
function Onclick(e) {
console.log(e.target.innerHTML);
}
</script>
样式部分,主要调整样式和实现鼠标悬停显示下一级菜单,样式看起来有些拙劣,凑合看吧

<style>
#dimension-tree {
position: absolute;
left: 0!important;
min-height: 688px;
border: 1pxsolidrgb(211,211,211);
top: -10px;
padding: 0;
width: 100px;
background: #f5f5f5;
z-index: 99;
}

#dimension-tree>li>a {
font-size: 14px;
color: rgb(15,14,14)!important;
text-decoration: none;
cursor: pointer;
display: block;
width: 100px;
}

#dimension-tree>li {
display: block!important;
height: 80px;
line-height: 80px;
}

.dimensionUl a {
font-size: 14px;
color: rgb(15,14,14)!important;
text-decoration: none;
display: block;
width: 100px;
cursor: pointer;
}

.dimensionLi:hover>.dimensionUl {
display: block;
}

.dimensionUl {
left: 100px;
top: 0;
width: 100px;
height: auto;
position: absolute;
background: #f5f5f5;
list-style: none;
padding: 0;
display: none;
}

.dimensionLi {
width: 100px;
height: 50px;
line-height: 50px;
text-align: center;
position: relative;
border: 1pxsolidrgb(211,211,211);
}

.dimensionLi:hover {
background: #aaa8a8;
}
</style>
html部分没啥好说的

<div>
<ul id="dimension-tree" #dimensionTree>
</ul>
</div>

阅读全文
0 0