做呼叫中心 IVR
时,路由节点是以树的形式展开的,正好项目中的角色权限用到了 jstree ,于是也顺路用了。但在看文档时,却发现了个问题,那就是没有和 ztree
类似的删除 icon
,官网只给出了点击选中树的节点,再点击删除按钮,把节点给删除方案,多了一步,而且鼠标来回点,麻烦。
既然发现问题,那就着手解决问题。经观察发现, jstree
树的每个节点主要信息都在 a
标签内,如下图所示
同时标签内的 class
都有 jstree-anchor
属性,那么可以利用 js
的 onmouseenter
、onmouseleave
来实现动态添加删除 icon
的 html
元素,再添加上官网的那个删除代码,就完成了功能,当然了删除 icon
可以从网上找,我是直接把 ztree
的那个删除 icon
给拿过来用 。
以下是 css
、js
代码
.treenode_remove {
line-height: 0;
margin-top: -1px;
width: 16px;
height: 16px;
display: inline-block;
vertical-align: middle;
border: 0 none;
cursor: pointer;
outline: 0;
background-color: transparent;
background-repeat: no-repeat;
background-attachment: scroll;
background-image:url("/img/ivr/treenode_remove.png")
}
$(document).on('mouseenter', '.jstree-anchor', function () {
var str = '<span class="button treenode_remove" title="删除节点" style=""></span>', width = $(this).width();
if (!$(this).find('span').hasClass('treenode_remove')) {
$(this).append(str);
$(this).width((width + 16) + 'px');
}
});
$(document).on('mouseleave', '.jstree-anchor', function () {
if ($(this).find('span').hasClass('treenode_remove')) {
$(this).find('.treenode_remove').remove();
$(this).width(($(this).width() - 16) + 'px');
}
});
$(document).on('click', '.treenode_remove', function () {
var ref = $('#tree_2').jstree(true),
sel = ref.get_selected();
if(!sel.length) { return false; }
ref.delete_node(sel);
});
看过代码的童鞋会奇怪为什么 a
标签宽度要加上 16
像素,这是为了保证操作都在 a
标签内,防止出现删除 icon
失效。最后,可能有的朋友会问了,为什么不直接拿 ztree
来用呢,你说为什么,因为我喜欢啊,^_^^_^
。