列表实现树形菜单

时间:2022-09-06 16:03:03
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>可展开列表</title>
<style>
.open{
list-style-image: url(img/add.png);
}

.close{
list-style-image: url(img/dec.png);
}

.open,.close{
cursor: pointer;
}

.open ul,.close ul{
list-style-image: none;
cursor: default;
}

.open ul{
display: none;
}

</style>
<script>
window.onload = setFunction;
function setFunction(){
var lis = document.getElementsByTagName('li');
for(var i =0;i<lis.length;i++){
if(lis[i].className == 'open')
lis[i].onmouseup = handlemouseup;
}
}
function handlemouseup(){
var state;
if(this.className == 'open'){
this.className='close';
state='';
}else if(this.className == 'close'){
this.className = 'open';
state = 'none';
}
var ulobj = this.getElementsByTagName('ul');
ulobj[0].style.display = state;
}
</script>
</head>
<body>
<ul>
<li class="open">
Layer1 item1
<ul>
<li>Layer2 item1</li>
<li>Layer2 item2</li>
<li>Layer2 item3</li>
</ul>
</li>
<li class="open">
Layer1 item2
<ul>
<li>Layer2 item1</li>
<li>Layer2 item2</li>
<li>Layer2 item3</li>
</ul>
</li>
<li class="open">
Layer1 item3
<ul>
<li>Layer2 item1</li>
<li>Layer2 item2</li>
<li>Layer2 item3</li>
</ul>
</li>
</ul>
</body>
</html>

第二层的ul标签会继承list-style-image以及cursor属性,所以还需要将它们设置为默认值

初始状态效果图:
列表实现树形菜单

点击效果图:
列表实现树形菜单