JavaScript 实现动态树形菜单的完整方案
作者:窗边听雨时间:2026-10-29 12:31:27浏览:268
本文详细介绍如何使用 JavaScript 构建动态树形菜单。通过定义包含 pid 和 ming 属性的数据结构,利用递归或循环生成嵌套的 ul/li HTML 结构。代码示例展示了如何动态添加按钮、处理点击事件以及计算元素高度,为前端开发者提供了一套完整的树形菜单实现思路与核心代码片段。
JavaScript 树形菜单实现概述
本文通过一个具体的实例,详细解析了使用 JavaScript 构建树形菜单的技术实现路径。该方案旨在为开发者提供可参考的代码逻辑与结构思路,便于在实际项目中应用或调整。
核心代码结构与 DOM 生成逻辑
var ME={
ini:{i:true,d:{},d1:{},h:0,h1:0,h2:0},
html:function(da,f){
var s='<ul'+(f?' class="f"':'')+'>';
for(var i=0,l=da.length;i<l;i++){
if(typeof(da[i].pid)=='object'){
s+='<li><button type="button" class="'+(i==0&&this.ini.i?'s1':(i+1==l?'s5':'s3'))+'" onclick="ME.yc(this)"></button><span><button type="button" class="r1"></button><a href="javascript:;">'+da[i].ming+'</a></span>';
this.ini.i=false;
s+=this.html(da[i].pid,(i+1==l));
}else{
s+='<li><button type="button" class="'+(i+1==l?'e3':'e1')+'"></button><span><button type="button" class="m1"></button><a href="https://www.jb51.net" target="mainFrame">'+da[i].ming+'</a></span>';
}
s+='</li>';
}
s+='</ul>';
return s;
},
st:function(id,da){
document.getElementById(id).innerHTML=this.html(da);
},
yc:function(a){
var s=a.className.substr(1);
if(s%2){
this.ini.d=a.parentNode.children[2];
this.ini.h1=this.hei(this.ini.d);
this.ini.h3=this.ini.h1/10;
this.yc1(1);
a.className='s'+(parseInt(s)+1);
a.parentNode.children[1].children[0].className='r2';
var ol=a.parentNode.parentNode._;
if(typeof(ol)=='object'){
this.ini.d1=ol;
this.ini.h=ol.offsetHeight;
this.ini.h2=this.ini.h/10;
this.yc2(1);
ol.parentNode.children[0].className='s'+(parseInt(ol.parentNode.children[0].className.substr(1))-1);
ol.parentNode.children[1].children[0].className='r1';
}
a.parentNode.parentNode._=a.parentNode.children[2];
}else{
this.ini.d1=a.parentNode.children[2];
this.ini.h=this.ini.d1.offsetHeight;
this.ini.h2=this.ini.h/10;
this.yc2(1);
a.className='s'+(parseInt(s)-1);
a.parentNode.children[1].children[0].className='r1';
a.parentNode.parentNode._='';
}
},
yc1:function(b){
var h1=ME.ini.h1-(11/(b+1)-1)*ME.ini.h3;
with(ME.ini.d.style){
height=h1+'px';
display='block';
}
if(b<10){
setTimeout('ME.yc1('+(b+1)+')',25);
}else{
ME.ini.d.style.display='block';
ME.ini.d.style.height='';
}
},
yc2:function(b){
var h1=(11/(b+1)-1)*ME.ini.h2;
with(ME.ini.d1.style){
height=h1+'px';
}
if(b<10){
setTimeout('ME.yc2('+(b+1)+')',25);
}else{
ME.ini.d1.style.display='';
ME.ini.d1.style.height='';
}
},
hei:function(a){
var b=a.cloneNode(true);
b.style.position='absolute';
b.style.display='block';
b.style.visibility='hidden';
a.parentNode.appendChild(b);
var h=b.offsetHeight;
a.parentNode.removeChild(b);
return h;
}
}
希望上述关于 JavaScript 程序设计的内容与代码示例,能为读者在开发树形菜单或类似交互组件时提供有价值的参考与帮助。
作者最新文章
anime.js 快速入门:怎么引入库并编写第一个 DOM 动画
2026-11-05 14:22:43
在线JS解密后变量名仍乱码?结合浏览器DevTools调试还原
2026-11-04 20:26:01
怎么在浏览器中运行JavaScript代码并查看输出结果
2026-11-04 09:07:33
JS 获取屏幕分辨率:window.screen.width 与 height 用法
2026-11-04 08:52:48
为什么推荐用DOMContentLoaded代替window.onload初始化JS
2026-11-04 08:42:33
