zTree(二)樹狀圖下拉框
阿新 • • 發佈:2019-02-11
需求
新增、修改終端需要選擇組織,組織是多級架構(樹狀圖顯示)。
思路
1、因為下拉框需要樹狀圖顯示,所以排除使用select
做下拉框,改用input
模擬下拉框
2、樹狀圖採用zTree外掛
開工
1、佈局
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/zTree.v3/3.5.33/js/jquery.ztree.core.min.js"></script>
<link href="https://cdn.bootcss.com/zTree.v3/3.5.33/css/zTreeStyle/zTreeStyle.min.css" rel="stylesheet">
<style>
.trg{
width: 0;
height: 0;
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-top: 6px solid black;;
position: absolute;
left:181px;
top :8px;
}
.org-select{
cursor: default;
z-index: -1;
width:200px;
}
</style>
<div style="position: relative;margin:90px;">
<input id="orgName" class="org-select" onclick="showTree()" readonly >
<!-- 模擬select點選框 以及option的text值顯示-->
<i class="trg"style="position: absolute;"></i>
<!-- 模擬select右側倒三角 -->
<input id="orgCode" type="hidden" name="orgCode" />
<!-- 儲存 模擬select的value值 -->
<!-- zTree樹狀圖 相對定位在其下方 -->
<div class="ztree" style="display:none; position: absolute;border:1px solid #4aa5ff;width:200px;">
<ul id="treeDemo"></ul>
</div>
</div>
2、js方法部分
//樹狀圖展示
var orgList =[
{ id:1, pId:0, name:"父節點1 - 展開", open:true},
{ id:11, pId:1, name:"父節點11 - 摺疊"},
{ id:111, pId:11, name:"葉子節點111"},
{ id:112, pId:11, name:"葉子節點112"},
{ id:113, pId:11, name:"葉子節點113"},
{ id:114, pId:11, name:"葉子節點114"},
{ id:12, pId:1, name:"父節點12 - 摺疊"},
{ id:121, pId:12, name:"葉子節點121"},
{ id:122, pId:12, name:"葉子節點122"},
{ id:123, pId:12, name:"葉子節點123"},
{ id:124, pId:12, name:"葉子節點124"},
];
var setting = {
data: {
simpleData: {
enable: true
}
},
//回撥
callback: {
onClick: zTreeOnClick
},
view: {
fontCss: { fontSize: "14px" }
}
};
//節點點選事件
function zTreeOnClick(event, treeId, treeNode) {
$('#orgName').val(treeNode.name);
$('#orgCode').val(treeNode.Id)
hideTree();
};
$(document).ready(function () {
//初始組織樹狀圖
$.fn.zTree.init($("#treeDemo"), setting, orgList);
});
//下拉框顯示 隱藏
function showTree(){
if($('.ztree').css('display') == 'none'){
$('.ztree').css('display','block');
} else{
$('.ztree').css('display','none');
}
$("body").bind("mousedown", onBodyDownByActionType);
}
function hideTree() {
$('.ztree').css('display','none');
$("body").unbind("mousedown", onBodyDownByActionType);
return false;
}
//區域外點選事件
function onBodyDownByActionType(event) {
if (event.target.id.indexOf('treeDemo') == -1){
if(event.target.id != 'selectDevType'){
hideTree();
}
}
}
效果圖