bootstrap-treeview1.2.0 给节点添加图片

bootstrap-treeview1.2.0官方只能给节点添加icon,而没有给节点设置image的方法,本文通过修改JS源码实现上述需求。

修改后的源码(只展示修改的部分):

/* =========================================================
 * bootstrap-treeview.js v1.2.0
 * =========================================================
 * Copyright 2013 Jonathan Miles
 * Project URL : http://www.jondmiles.com/bootstrap-treeview
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

;(function ($, window, document, undefined) {

    /*global jQuery, console*/

    'use strict';

    const pluginName = 'treeview';

    const _default = {};

    _default.settings = {

        injectStyle: true,

        levels: 2,

        expandIcon: 'glyphicon glyphicon-plus',
        collapseIcon: 'glyphicon glyphicon-minus',
        emptyIcon: 'glyphicon',
        nodeIcon: '',
        selectedIcon: '',
        checkedIcon: 'glyphicon glyphicon-check',
        uncheckedIcon: 'glyphicon glyphicon-unchecked',

        color: undefined, // '#000000',
        backColor: undefined, // '#FFFFFF',
        borderColor: undefined, // '#dddddd',
        onhoverColor: '#F5F5F5',
        selectedColor: '#FFFFFF',
        selectedBackColor: '#428bca',
        searchResultColor: '#D9534F',
        searchResultBackColor: undefined, //'#FFFFFF',

        enableLinks: false,
        highlightSelected: true,
        highlightSearchResults: true,
        showBorder: true,
        showIcon: true,
        showCheckbox: false,
        showTags: false,
        multiSelect: false,

        /**
         * 给 bootstrap-treeview 添加 “是否显示图片” 属性,icon 优先级高于 image
         * @author yupurpley
         * @date 2021/4/25 14:28
         */
        showImage: false,

        // Event handlers
        onNodeChecked: undefined,
        onNodeCollapsed: undefined,
        onNodeDisabled: undefined,
        onNodeEnabled: undefined,
        onNodeExpanded: undefined,
        onNodeSelected: undefined,
        onNodeUnchecked: undefined,
        onNodeUnselected: undefined,
        onSearchComplete: undefined,
        onSearchCleared: undefined,
    };

    // Starting from the root node, and recursing down the
    // structure we build the tree one node at a time
    Tree.prototype.buildTree = function (nodes, level) {

        if (!nodes) return;
        level += 1;

        const _this = this;
        $.each(nodes, function addNodes(id, node) {

            const treeItem = $(_this.template.item)
                .addClass('node-' + _this.elementId)
                .addClass(node.state.checked ? 'node-checked' : '')
                .addClass(node.state.disabled ? 'node-disabled' : '')
                .addClass(node.state.selected ? 'node-selected' : '')
                .addClass(node.searchResult ? 'search-result' : '')
                .attr('data-nodeid', node.nodeId)
                .attr('style', _this.buildStyleOverride(node));

            // Add indent/spacer to mimic tree structure
            for (let i = 0; i < (level - 1); i++) {
                treeItem.append(_this.template.indent);
            }

            // Add expand, collapse or empty spacer icons
            let classList = [];
            if (node.nodes) {
                classList.push('expand-icon');
                if (node.state.expanded) {
                    classList.push(_this.options.collapseIcon);
                }
                else {
                    classList.push(_this.options.expandIcon);
                }
            }
            else {
                classList.push(_this.options.emptyIcon);
            }

            treeItem
                .append($(_this.template.icon)
                    .addClass(classList.join(' '))
                );


            /**
             * Add node icon
             * @author yupurpleu
             * @date 2021/4/25 14:34
             */
            if (_this.options.showIcon && !(_this.options.showImage && node.image)) {

                classList = ['node-icon'];

                classList.push(node.icon || _this.options.nodeIcon);
                if (node.state.selected) {
                    classList.pop();
                    classList.push(node.selectedIcon || _this.options.selectedIcon ||
                        node.icon || _this.options.nodeIcon);
                }

                treeItem
                    .append($(_this.template.icon)
                        .addClass(classList.join(' '))
                    );
            }

            /**
             * Add node image
             * @author yupurpleu
             * @date 2021/4/25 14:34
             */
            if (_this.options.showImage && node.image) {
                classList = ['node-image'];

                classList.push(node.image);

                treeItem
                    .append($(_this.template.image)
                        .addClass(classList.join(' '))
                        .css({
                            'background-image': "url('" + node.image + "')",
                            'background-size': '100% 100%',
                            'display': 'inline-block',
                            'vertical-align': 'bottom',
                            'width': '20px',
                            'height': '20px',
                            'margin-right': '5px'
                        })
                    );
            }

            // Add check / unchecked icon
            if (_this.options.showCheckbox) {

                classList = ['check-icon'];
                if (node.state.checked) {
                    classList.push(_this.options.checkedIcon);
                }
                else {
                    classList.push(_this.options.uncheckedIcon);
                }

                treeItem
                    .append($(_this.template.icon)
                        .addClass(classList.join(' '))
                    );
            }

            // Add text
            if (_this.options.enableLinks) {
                // Add hyperlink
                treeItem
                    .append($(_this.template.link)
                        .attr('href', node.href)
                        .append(node.text)
                    );
            }
            else {
                // otherwise just text
                treeItem
                    .append(node.text);
            }

            // Add tags as badges
            if (_this.options.showTags && node.tags) {
                $.each(node.tags, function addTag(id, tag) {
                    treeItem
                        .append($(_this.template.badge)
                            .append(tag)
                        );
                });
            }

            // Add item to the tree
            _this.$wrapper.append(treeItem);

            // Recursively add child ndoes
            if (node.nodes && node.state.expanded && !node.state.disabled) {
                return _this.buildTree(node.nodes, level);
            }
        });
    };

    Tree.prototype.template = {
        list: '<ul class="list-group"></ul>',
        item: '<li class="list-group-item"></li>',
        indent: '<span class="indent"></span>',
        icon: '<span class="icon"></span>',

        /**
         * 声明 image 类名
         * @author yupurpleu
         * @date 2021/4/25 14:34
         */
        image: '<span class="image"></span>',

        link: '<a href="#" style="color:inherit;"></a>',
        badge: '<span class="badge"></span>'
    };

})(jQuery, window, document);

前端使用:

$('#tree').treeview({
    expandIcon: 'glyphicon glyphicon-triangle-right',
    collapseIcon: 'glyphicon glyphicon-triangle-bottom',
    showImage: true,
    image: '/images/type.png',  // 添加图片
    showBorder: false,
    data: defaultData,
})

版权声明:本文为yupurpleu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。