在bootstrap中使用ztree插件做树形架构,由于觉得原始的树形不够美观,所以改了其中的css插件
demo演示,以及各种属性的用法网站: http://www.treejs.cn/v3/demo.php#_107
修改页面风格网站: http://www.lai18.com/content/2450914.html?from=cancel
增删改查以及拖拽功能网站: http://www.cnblogs.com/lori/archive/2013/07/04/3171655.html
参考以上网站,可根据的自己的需要进行修改
下面贴出我在做项目时的代码(前端用的是bootstrap框架,对默认的css进行了修改)
1)先引入文件(一个css,一个js文件)
<link rel="stylesheet" href="${contextPath}/static/assets/css/zTreeStyle/metro.css"/>
"${contextPath}/static/assets/js/ztree-3.5/jquery.ztree.all-3.5.js"
2)页面
//注意这个地方的引入,否则页面不会显示任何东西
<div id="organizationTree" class="ztree" style="560px; overflow:auto;"></div>
3) js代码
var zTree;
var setting = {
check: {
enable: true
},
async: {
enable: true, //开启异步加载处理
contentType: "application/json;charset=utf-8",
// dataFilter: filter,//用于对 Ajax 返回数据进行预处理的函数
dataType: "json",
url: "${contextPath}/organization/getOrganizations/list", //加载后台数据
//autoParam: ["id", "name"],
type: "post",
//autoParam:[]
otherParam: []
// dataFilter: filter //用于对 Ajax 返回数据进行预处理的函数
},
view: {
expandSpeed: "",//zTree 节点展开、折叠时的动画速度,设置方法同 JQuery 动画效果中 speed 参数。
addHoverDom: addHoverDom, //用于当鼠标移动到节点上时,显示用户自定义控件,显示隐藏状态同 zTree 内部的编辑、删除按钮
removeHoverDom: removeHoverDom, //设置鼠标移到节点上,在后面显示一个按钮
selectedMulti: false, // 禁止多点同时选中的功能
fontCss: setFontCss_ztree //样式设置
},
edit: {
enable: true, //设置 zTree 进入编辑状态
editNameSelectAll: true,
removeTitle: '删除',
renameTitle: '编辑',
showRemoveBtn: true,
showRenameBtn: true,
},
data: {
keep: {
parent: true,
leaf: false
},
simpleData: {
enable: true
}
},
callback: {
beforeRemove: beforeRemove, //点击删除时触发,用来提示用户是否确定删除
beforeEditName: beforeEditName, //点击编辑时触发,用来判断该节点是否能编辑
// beforeRename:beforeRename,//编辑结束时触发,用来验证输入的数据是否符合要求
// onRemove:onRemove,//删除节点后触发,用户后台操作
// onRename:onRename,//编辑后触发,用于操作后台
// beforeDrag:beforeDrag,//用户禁止拖动节点
// onClick:clickNode//点击节点触发的事件
// onNodeCreated: zTreeOnNodeCreated
onAsyncSuccess: zTreeOnAsyncSuccess, //默认展开所有节点
/*拖动回调*/
beforeDrag: beforeDrag,
// beforeDrop: beforeDrop,
// beforeDragOpen: beforeDragOpen,
// onDrag: onDrag,
onDrop: onDrop
}
};
//设置鼠标移到节点上,在后面显示一个按钮
function removeHoverDom(treeId, treeNode) {
$("#addBtn_" + treeNode.tId).unbind().remove();
}
//加载树结构
function loadTreeData() {
zTree = $.fn.zTree.init($("#organizationTree"), setting);
}
function reloadTree() {
loadTreeData();
}
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
zTree.expandAll(true);
}
//实现拖拽
var log, className = "dark";
var treeID = "treeDemo";
var curDragNodes, autoExpandNode;
var newCount = 1;
function beforeDrag(treeId, treeNodes) {
className = (className === "dark" ? "" : "dark");
for (var i = 0, l = treeNodes.length; i < l; i++) {
if (treeNodes[i].drag === false) {
curDragNodes = null;
return false;
} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
curDragNodes = null;
return false;
}
}
curDragNodes = treeNodes;
return true;
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
if (moveType == "inner") {
$.ajax({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
//传送请求数据
data: JSON.stringify({
oper: "changeParent",
primaryKey: targetNode.id,
primaryKeys: [treeNodes[0].id]
}),
// data: { id: treeNodes[0].id, pid: targetNode.id, name: treeNodes[0].name, moveType: moveType, isCopy: isCopy },
dataType: "json",
method: 'post',
success: function (data) {
alert('拖拽成功!');
}
});
} else {
$.ajax({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
//传送请求数据
data: JSON.stringify({
oper: "setSameParent",
primaryKey: targetNode.id,
primaryKeys: [treeNodes[0].id]
}),
// data: { id: treeNodes[0].id, pid: targetNode.id, name: treeNodes[0].name, moveType: moveType, isCopy: isCopy },
dataType: "json",
method: 'post',
success: function (data) {
alert('拖拽成功!');
}
});
}
}
function keydownInput() {
var event = event || window.event;
if (event.keyCode == 13) {
searchOrg();
}
}
function searchOrg() {
//searchByFlag_ztree(treeId, search_orgainzation, "");
searchByFlag_ztree('organizationTree', 'search_orgainzation', "");
/*var searchName = $("#search_orgainzation").val();
$.ajax({
url: "
${contextPath}/organization/getOrganizations/list?keyword="+searchName,
type : 'POST',
dataType : 'json',
success : function(data) {
}
});*/
}
/**
* 收起树:只展开根节点下的一级节点
* @param treeId
*/
function close_ztree(treeId) {
var treeObj = $.fn.zTree.getZTreeObj(treeId);
var nodes = treeObj.transformToArray(treeObj.getNodes());
var nodeLength = nodes.length;
for (var i = 0; i < nodeLength; i++) {
if (nodes[i].id == '0') {
//根节点:展开
treeObj.expandNode(nodes[i], true, true, false);
} else {
//非根节点:收起
treeObj.expandNode(nodes[i], false, true, false);
}
}
}
/**
* 搜索树,高亮显示并展示【模糊匹配搜索条件的节点s】
* @param treeId
* @param search_orgainzation 文本框的id
*/
function searchOrganization(treeId, search_orgainzation) {
searchByFlag_ztree(treeId, search_orgainzation, "");
}
/**
* 搜索树,高亮显示并展示【模糊匹配搜索条件的节点s】
* @param treeId
* @param searchConditionId 搜索条件Id
* @param flag 需要高亮显示的节点标识
*/
function searchByFlag_ztree(treeId, search_orgainzation, flag) {
//<1>.搜索条件
var searchCondition = $("#search_orgainzation").val();
//<2>.得到模糊匹配搜索条件的节点数组集合
var highlightNodes = new Array();
if (searchCondition && searchCondition != "") {
// var treeObj = $.fn.zTree.init($("#organizationTree"), setting,treeId);
// var treeObj=reloadTree(treeId);
var treeObj = $.fn.zTree.getZTreeObj(treeId);
highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
//<3>.高亮显示并展示【指定节点s】
highlightAndExpand_ztree(treeId, highlightNodes, flag);
}
}
/**
* 高亮显示并展示【指定节点s】
* @param treeId
* @param highlightNodes 需要高亮显示的节点数组
* @param flag 需要高亮显示的节点标识
*/
function highlightAndExpand_ztree(treeId, highlightNodes, flag) {
var treeObj = $.fn.zTree.getZTreeObj(treeId);
//<1>. 先把全部节点更新为普通样式
var treeNodes = treeObj.transformToArray(treeObj.getNodes());
for (var i = 0; i < treeNodes.length; i++) {
treeNodes[i].highlight = false;
treeObj.updateNode(treeNodes[i]);
}
//<2>.收起树, 只展开根节点下的一级节点
close_ztree(treeId);
//<3>.把指定节点的样式更新为高亮显示,并展开
if (highlightNodes != null) {
for (var i = 0; i < highlightNodes.length; i++) {
if (flag != null && flag != "") {
if (highlightNodes[i].flag == flag) {
//高亮显示节点,并展开
highlightNodes[i].highlight = true;
treeObj.updateNode(highlightNodes[i]);
//高亮显示节点的父节点的父节点....直到根节点,并展示
var parentNode = highlightNodes[i].getParentNode();
var parentNodes = getParentNodes_ztree(treeId, parentNode);
treeObj.expandNode(parentNodes, true, false, true);
treeObj.expandNode(parentNode, true, false, true);
}
} else {
//高亮显示节点,并展开
highlightNodes[i].highlight = true;
treeObj.updateNode(highlightNodes[i]);
//高亮显示节点的父节点的父节点....直到根节点,并展示
var parentNode = highlightNodes[i].getParentNode();
var parentNodes = getParentNodes_ztree(treeId, parentNode);
treeObj.expandNode(parentNodes, true, false, true);
treeObj.expandNode(parentNode, true, false, true);
}
}
}
}
/**
* 递归得到指定节点的父节点的父节点....直到根节点
*/
function getParentNodes_ztree(treeId, node) {
if (node != null) {
var treeObj = $.fn.zTree.getZTreeObj(treeId);
var parentNode = node.getParentNode();
return getParentNodes_ztree(treeId, parentNode);
} else {
return node;
}
}
/**
* 设置树节点字体样式
*/
function setFontCss_ztree(treeId, treeNode) {
if (treeNode.id == 0) {
//根节点
return {color: "#333", "font-weight": "bold"};
} else if (treeNode.isParent == false) {
//叶子节点
return (!!treeNode.highlight) ? {color: "#ff0000", "font-weight": "bold"} : {
color: "#660099",
"font-weight": "normal"
};
} else {
//父节点
return (!!treeNode.highlight) ? {color: "#ff0000", "font-weight": "bold"} : {
color: "#333",
"font-weight": "normal"
};
}
}
//添加新的节点
function addHoverDom(treeId, treeNode) {
$("#priorityTip").hide();
var sObj = $("#" + treeNode.tId + "_span");
if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
+ "' title='add node' onfocus='this.blur();'></span>";
sObj.after(addStr);
var btn = $("#addBtn_" + treeNode.tId);
if (btn) btn.bind("click", function () {
var zTree = $.fn.zTree.getZTreeObj("organizationTree");
// if (confirm("确认为 " + treeNode.name + " 添加子节点吗?")) {
$("#modal-table").modal("show");
//设置新增窗口的一些属性,重置表单中的值
document.getElementById("title1").innerHTML = "新增组织架构";
$("#editOrganization").addClass("hidden");
$("#addOrganization").removeClass("hidden");
$("#form_organizationform")[0].reset();
$("#form_organizationParent").val(treeNode.id);
$("#form_organizationParentName").val(treeNode.name);
});
}
//编辑前的验证
function beforeEditName(treeId, treeNode) {
$("#priorityTip").hide();
document.getElementById("title1").innerHTML = "编辑组织架构";
$("#addOrganization").addClass("hidden");
$("#editOrganization").removeClass("hidden");
var parentId = treeNode.pId;
$.ajax({
url: "${contextPath}/organization/getOrganizations/query?id=" + parentId,
type: 'POST',
dataType: 'json',
success: function (data) {
$("#form_organizationParentName").val(data.orgname);
}
});
$("#form_organizationORG_ID").val(treeNode.id);
$("#form_organizationName").val(treeNode.name);
$("#form_organizationParent").val(treeNode.pId);
$("#form_organizationORG_BRIEF").val(treeNode.orgbrief);
$("#form_organizationORG_CODE").val(treeNode.orgcode);
if (treeNode.isactive) {
$("#form_organizationIsactive").val("true");
} else {
$("#form_organizationIsactive").val("false");
}
$("#form_organizationPRIORITY").val(treeNode.priority);
$("#form_organizationADDWAY").val(treeNode.addway);
$("#form_organizationDesc").val(treeNode.description);
$("#modal-table").modal("show");
}
//删除节点信息
function beforeRemove(treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("organizationTree");
zTree.selectNode(treeNode);
var selectNodeId = treeNode.id;
var selectNodeParentId = treeNode.pId;
bootbox.confirm({
title: "提示",
message: "删除组织架构[<font class='red'>" + treeNode.name + "</font>]" +
"<br/><input type='radio' id='delOneorg' name='delOrg' checked/>如有下级架构,将会自动并入本级架构中" +
"<br/><input type='radio' id='delPartOrg' name='delOrg'/>如有下级架构,将会一起被删除",
buttons: {
confirm: {
label: "确认",
//className: "btn-success",
},
cancel: {
label: "取消",
//className: "btn-success",
}
},
callback: function (result) {
if (result) {//OK
if ($('#delOneorg').is(':checked')) {
//开始发送数据
$.ajax({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
dataType: "json",
method: 'post',
//传送请求数据
data: JSON.stringify({
oper: "delMerge",
entry: {
id: selectNodeId,
parentid: selectNodeParentId
}
}),
success: function (data_) {
alert('删除成功!');
//重载tree数据
reloadTree();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('删除失败!');
}
});
} else {
$.ajax({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
dataType: "json",
method: 'post',
//传送请求数据
data: JSON.stringify({
oper: "del",
primaryKey: selectNodeId
}),
success: function (data_) {
alert('删除成功!');
//重载tree数据
reloadTree();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('删除失败!');
}
});
}
}
}
});
return false;
}
function addOrganization() {
if ($("#form_organizationName").val().length == 0) {
$("#form_organizationName").focus();
return false;
}
if ($("#form_organizationIsactive").val().length == 0) {
$("#form_organizationIsactive").focus();
return false;
}
if ($("#form_organizationPRIORITY").val().length == 0||!isNumber($("#form_organizationPRIORITY").val())) {
if(!isNumber($("#form_organizationPRIORITY").val()))
$("#form_organizationPRIORITY").focus();
$("#priorityTip").show();
return false;
}
//开始发送数据
$.ajax
({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
dataType: "json",
method: 'post',
//传送请求数据
data: JSON.stringify({
oper: "update",
entry: {
id: -1,
parentid: $("#form_organizationParent").val(),
orgname: $("#form_organizationName").val(),
orgbrief: $("#form_organizationORG_BRIEF").val(),
orgcode: $("#form_organizationORG_CODE").val(),
isactive: $("#form_organizationIsactive").val(),
priority: $("#form_organizationPRIORITY").val(),
addway: $("#form_organizationADDWAY").val(),
description: $("#form_organizationDesc").val()
}
}),
success: function (data_) {
//alert(data_);
alert(data_.message);
//重载grid数据
reloadTree();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error:" + textStatus);
}
});
//$("#add_proj").modal("show");
$("#modal-table").modal("hide");
}
function editOrganization() {
if ($("#form_organizationName").val().length == 0) {
$("#form_organizationName").focus();
return false;
}
if ($("#form_organizationIsactive").val().length == 0) {
$("#form_organizationIsactive").focus();
return false;
}
if ($("#form_organizationPRIORITY").val().length == 0||!isNumber($("#form_organizationPRIORITY").val())) {
if(!isNumber($("#form_organizationPRIORITY").val()))
$("#form_organizationPRIORITY").focus();
$("#priorityTip").show();
return false;
}
//开始发送数据
$.ajax
({
contentType: "application/json",
url: "${contextPath}/organization/operateOrg",
dataType: "json",
method: 'post',
//传送请求数据
data: JSON.stringify({
oper: "update",
entry: {
id: $("#form_organizationORG_ID").val(),
parentid: $("#form_organizationParent").val(),
orgname: $("#form_organizationName").val(),
orgbrief: $("#form_organizationORG_BRIEF").val(),
orgcode: $("#form_organizationORG_CODE").val(),
isactive: $("#form_organizationIsactive").val(),
priority: $("#form_organizationPRIORITY").val(),
description: $("#form_organizationDesc").val()
}
}),
success: function (data_) {
//alert(data_);
alert(data_.message);
//重载grid数据
reloadTree();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error:" + textStatus);
}
});
//$("#add_proj").modal("show");
$("#modal-table").modal("hide");
}