Bootstrap框架建立树形菜单(Tree)的实例代码

2020-05-24 21:36:41易采站长站整理

width:1px
}
.tree li::after {
border-top:1px solid #999;
height:20px;
top:25px;
width:25px
}
.tree li span {
-moz-border-radius:5px;
-webkit-border-radius:5px;
border:1px solid #999;
border-radius:5px;
display:inline-block;
padding:3px 8px;
text-decoration:none
}
.tree li.parent_li>span {
cursor:pointer
}
.tree>ul>li::before, .tree>ul>li::after {
border:0
}
.tree li:last-child::before {
height:30px
}
.tree li.parent_li>span:hover, .tree li.parent_li>span:hover+ul li span {
background:#eee;
border:1px solid #94a0b4;
color:#000
}

JS CODE


<script type="text/javascript">
//为节点添加展开,关闭的操作
$(function(){
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});
</script>

效果:

这里写图片描述 

一棵符合Bootstrap风格的树就这么建造完成了,优点自不用说:整洁,美观。

这是一个demo,所以树中的值都是写死在html里面的,但是在实际项目中,树形菜单一般都是动态生成的,而Bootstrap却没有为我们提供一个类似TreeView那样的控件,只需要绑定上数据就可以动态生成一棵树,所以生成树的逻辑都需要我们手动用JS代码进行编写。这个过程着实有点繁琐,递归+嵌套。。

当然市面上也有很多封装好的一些树形菜单的插件,DTree,TreeList widget,Ztree,jQuery等等,就是外观和Bootstrap框架有点不搭。

有这么个折中的办法,就是取长补短,把Bootstrap的样式应用到这些封装好的树形插件上来满足需求。