jstree 添加行内删除 icon

做呼叫中心 IVR 时,路由节点是以树的形式展开的,正好项目中的角色权限用到了 jstree ,于是也顺路用了。但在看文档时,却发现了个问题,那就是没有和 ztree 类似的删除 icon,官网只给出了点击选中树的节点,再点击删除按钮,把节点给删除方案,多了一步,而且鼠标来回点,麻烦。

在这里插入图片描述

既然发现问题,那就着手解决问题。经观察发现, jstree 树的每个节点主要信息都在 a 标签内,如下图所示

在这里插入图片描述

同时标签内的 class 都有 jstree-anchor 属性,那么可以利用 jsonmouseenteronmouseleave 来实现动态添加删除 iconhtml 元素,再添加上官网的那个删除代码,就完成了功能,当然了删除 icon 可以从网上找,我是直接把 ztree 的那个删除 icon 给拿过来用 。

以下是 cssjs 代码

.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 来用呢,你说为什么,因为我喜欢啊,^_^^_^

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值