jquery 生撸 树形树状结构Tree 树形控件
jquery 生撸 树形树状结构Tree 树形控件
直接上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.tree {
border: solid red 1px;
width: 100px;
margin-left: 20px;
cursor: pointer;
position: relative;
padding-left: 20px;
}
.treeSon {
border: solid blue 1px;
display: none;
}
.triangle{
position: absolute;
top: 7px;
left: 5px;
width: 5px;
height: 5px;
border: solid red 1px;
border-top: transparent;
border-left: transparent;
transform: rotate(-45deg);
transition: .5s;
}
.triangleActive{
transform: rotate(45deg);
}
</style>
</head>
<body>
<div id="main">
</div>
<script type="text/javascript" src="new_file.js"></script>
<script type="text/javascript">
var data = [{
name: "一级",
id: "tree1",
son: []
},
{
name: "二级",
id: "tree2",
son: [{
name: "二级-1",
id: "tree2-1",
son: [{
name: "二级-1-1",
id: "tree2-1-1",
son: []
}, {
name: "二级-1-2",
id: "tree2-1-2",
son: []
}]
}, {
name: "二级-2",
id: "tree2-2",
son: []
}]
}, {
name: "三级",
id: "tree3",
son: [{
name: "二级-2",
id: "tree2-2",
son: []
}]
},
]
function tree(id, data) {
var dom = ''
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
dom += '<div class="tree" >'
dom += data[i].name
if (data[i].son.length > 0) {
dom += '<div class="treeSon" id="' + data[i].id + '"> </div>'
dom+='<div class="triangle"></div>'
}
dom += '</div>'
}
$('#' + id).html(dom)
}
}
tree('main', data)
function digui(data) {
for (var i = 0; i < data.length; i++) {
tree(data[i].id, data[i].son)
if (data[i].son.length > 0) {
digui(data[i].son)
}
}
}
digui(data)
$(".tree").click(function() {
if ($(this).children('.treeSon').css("display") == "none") {
$(this).children('.treeSon').show()
$(this).children('.triangle').addClass("triangleActive")
} else {
$(this).children('.treeSon').hide()
$(this).children('.triangle').removeClass("triangleActive")
}
})
$(".treeSon").click(function(event) {
event.stopPropagation();
})
</script>
</body>
</html>
好用的批爆