效果图
需要引用到jquery
html部分
<body>
<div id="menuTree" class="menuTree"></div>
</body>
css部分
.menuTree {
margin-left: 0px;
}
.menuTree label {
padding-left: 1px;
display: block;
}
.menuTree input[type="radio"]{
width: 18px;
height: 16px;
appearance: none;
position: relative;
vertical-align: text-bottom;
}
.menuTree input[type="radio"]:before{
content: '';
width: 18px;
height: 18px;
border: 1px solid #2D92FF;
background-color: #fff;
display: inline-block;
border-radius: 50%;
vertical-align: middle;
margin-top: -4px;
}
.menuTree input[type="radio"]:checked:before{
content: '';
width: 18px;
height: 18px;
border: 1px solid #2D92FF;
background:#2D92FF;
display: inline-block;
border-radius: 50%;
vertical-align: middle;
margin-top: -4px;
}
.menuTree input[type="radio"]:checked:after{
content: '';
width: 10px;
height: 5px;
border: 2px solid white;
border-top: transparent;
border-right: transparent;
text-align: center;
display: block;
position: absolute;
top: 5px;
left: 4px;
vertical-align: middle;
transform: rotate(-45deg);
}
.menuTree input[type="radio"]:checked+label{
color: #2D92FF;
}
.menuTree label ul {
overflow: hidden;
display: none;
height: auto;
margin: 0;
padding-left: 40px !important;
}
.menuTree span {
display: inline-block;
height: 30px;
line-height: 30px;
padding-left: 5px;
margin: 1px 0;
cursor: pointer;
}
.menuTree span:hover {
background-color: #e6e6e6;
color: #FF1A36;
}
js 部分
var json = [{
"leval": "1",
"name": "楼栋管理",
"list": [{
//显示名称
"leval": "2",
//用户等级
"name": "科研教学楼",
},{
//显示名称
"leval": "2",
//用户等级
"name": "科研教学楼",
},
{
//显示名称
"leval": "2",
//用户等级
"name": "科研教学楼",
}
]
}
]
/*递归实现获取无级树数据并生成DOM结构*/
var str = "";
var forTree = function(o) {
for (var i = 0; i < o.length; i++) {
var urlstr = "";
try {
urlstr = "<label><input type='radio' name='radio'><span>" + o[i]["name"] + "</a></span><ul>";
str += urlstr;
if (o[i]["list"] != null) {
forTree(o[i]["list"]);
}
str += "</ul></label>";
} catch (e) {}
}
return str;
}
/*添加无级树*/
document.getElementById("menuTree").innerHTML = forTree(json);
/*树形菜单*/
var menuTree = function() {
//给有子对象的元素加
$("#menuTree ul").each(function(index, element) {
var ulContent = $(element).html();
var spanContent = $(element).siblings("span").html();
if (ulContent) {
$(element).siblings("span").html(spanContent)
}
});
$("#menuTree").find("label span").click(function() {
var ul = $(this).siblings("ul");
if (ul.find("label").html() != null) {
if (ul.css("display") == "none") {
ul.show(300);
} else {
ul.hide(300);
}
}
})
}()
/*树形列表展开*/
$("#btn_open").click(function() {
$("#menuTree ul").show(300);
})
/*收缩*/
$("#btn_close").click(function() {
$("#menuTree ul").hide(300);
})