无限极多选下拉框

项目中用到的,自己写的插件。

没法上传代码= =、直接上代码吧。

js

/**
 * author beanLau
 * 使用方法myselecttree = $(dom).zdSelectTree(options)
 * options配置参数如下
 * {
 *  data: [],下拉树数据,格式见zdSelectTreeDemo.html中参数
    maxHeight:'148',内容选择框高度
    position:'bottom',内容选择框显示位置。默认bottom   值:'bottom' || 'top'
    selectData:[],用来保存选中数据,初始化传至不生效,不要传这个参数,设置默认值请使用setSelectData方法。
    selectObj:[],用来保存选中数据,初始化传至不生效,不要传这个参数,设置默认值请使用setSelectData方法。
    multiple:true,是否支持多选,默认为多选,可选址 true || false
    changeCb:null, 树形无限极下拉框值修改后的回调 类型为function 否则不执行。
    placeholder:'请选择' 未选中是输入框显示的值
 * }
 * 对外提供的方法
 * myselecttree.setSelectData(selectData) selectData为字符串数组例如['123','234','2345'] 为选中值的id属性
 * myselecttree.getSelectValue() 获取选中的值。返回结果为['123','3112'] 数组内容为选中的id
 * myselecttree.getSelectObj() 获取选中的值。返回结果为[{id:'123',name:'name',parentid:'2123'}] 数组内容为选中的数据对象
 */
(function ($, window, document, undefined) {
    //定义Beautifier的构造函数
    var ZdSelectTree = function (ele, opt) {
        this.$element = ele,
            this.defaults = {
                data: [],
                maxHeight: '148',
                position: 'bottom',
                selectData: [],
                selectObj: [],
                multiple: true,
                changeCb: null,
                placeholder: '请选择',
                defaultSelect:[]
            },
            this.options = $.extend({}, this.defaults, opt)
    }
    //定义ZdSelectTree的方法
    ZdSelectTree.prototype = {
        //通过id 递归获取对应数据
        getRowDataForId: function (id, data) {
            var _this = this;
            var rowData;
            $.each(data, function (i, item) {
                if (item.id == id) {
                    rowData = item;
                    return false;
                } else if (item.children) {
                    rowData = _this.getRowDataForId(id, item.children);
                }
            })
            return rowData;
        },
        selectCb: function (obj) { //设置选中的值
            var _this = this;
            if (!_this.options.multiple) {//如果是单选,直接设置值
                _this.options.selectData = [obj.id];
                _this.options.selectObj = [obj];
                _this.$element.find(".zd-selecttree-checked-content").html("<span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span><span class='echo-span' _id=" + obj.id + ">" + obj.name + ",</span>");
            } else {//多选
                //给保存选中值的变量赋值开始
                var _index = -1;
                $.each(_this.options.selectData, function (index, item) {
                    if (item == obj.id) {
                        _index = index;
                    }
                })
                if (_index == -1) {
                    _this.options.selectData.push(obj.id);
                }

                _index = -1;
                $.each(_this.options.selectObj, function (index, item) {
                    if (item.id == obj.id) {
                        _index = index;
                    }
                })
                if (_index == -1) {
                    _this.options.selectObj.push(obj);
                }
                //给保存选中值的变量赋值结束

                //判断回显的span是否存在
                if (_this.$element.find("span[_id='" + obj.id + "']").length == 0) {
                    _this.$element.find(".zd-selecttree-checked-content").append('<span class="echo-span" _id=' + obj.id + '>' + obj.name + ',</span>');
                }
            }
            _this.dataChangeCb();
            if (typeof _this.options.changeCb == 'function') {
                _this.options.changeCb(_this.options.selectData, _this.options.selectObj)
            }
        },
        dataChangeCb: function () {//数据改变以后回调,用来判断placeholder是否显示
            var _this = this;
            if (_this.options.selectData.length != 0) {
                _this.$element.find('.zdselecttree-placeholder').hide();
            } else {
                _this.$element.find('.zdselecttree-placeholder').show();

            }
        },
        unselectCb: function (obj) {//移除选中的值
            var _this = this;
            if (!_this.options.multiple) {//如果是单选,直接设置值
                _this.options.selectData = [];
                _this.options.selectObj = [];
                _this.$element.find(".zd-selecttree-checked-content").html("<span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span>");
            } else {//多选 首先移除只
                var _index = -1;
                $.each(_this.options.selectData, function (index, item) {
                    if (item == obj.id) {
                        _index = index;
                    }
                })
                if (_index > -1) {
                    _this.options.selectData.splice(_index, 1);
                }

                _index = -1;
                $.each(_this.options.selectObj, function (index, item) {
                    if (item.id == obj.id) {
                        _index = index;
                    }
                })
                if (_index > -1) {
                    _this.options.selectObj.splice(_index, 1);
                }

                //判断回显的span是否存在
                if (_this.$element.find("span[_id='" + obj.id + "']").length > 0) {
                    _this.$element.find("span[_id='" + obj.id + "']").remove();
                }
            }
            _this.dataChangeCb();
            if (typeof _this.options.changeCb == 'function') {
                _this.options.changeCb(_this.options.selectData, _this.options.selectObj)
            }
        },
        setSelectData: function (selectData) {//设置下拉框值
            var _this = this;
            if (selectData instanceof Array && selectData.length != 0) {
                _this.$element.find('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active');
                $.each(selectData, function (index, item) {
                    var obj = {};
                    obj.id = item;
                    obj.name = _this.$element.find("li[_id='" + item + "']").attr('_name');
                    obj.parentid = _this.$element.find("li[_id='" + item + "']").attr('_parentid');
                    _this.selectCb(obj);
                    _this.$element.find("li[_id='" + item + "']").children('.zdselecttree-select-icon').addClass('zdselecttree-select-icon-active')
                })
            } else if (selectData.length == 0) {
                _this.$element.find('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active');
                _this.$element.find(".zd-selecttree-checked-content").html("<span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span>");
                _this.options.selectData = [];
                _this.options.selectObj = [];
            }
        },
        clearSelectData: function () {//清空下拉框值
            var _this = this;
            _this.$element.find('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active');
            _this.$element.find(".zd-selecttree-checked-content").html("<span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span>");
            _this.options.selectData = [];
            _this.options.selectObj = [];
        },
        getSelectValue: function () {
            var _this = this;
            return _this.options.selectData
        },
        getSelectObj: function () {
            var _this = this;
            return _this.options.selectObj
        },
        getSelectText:function(){
            var selectText = [];
            $.each(this.options.selectObj,function(id,item){
                selectText.push(item.name);
            })
            return selectText;
        },
        bindEvent: function () {
            var _this = this;
            $('html').click(function (e) {
                var tag = false;
                $('.zd-selecttree-content').each(function (index, item) {
                    tag = $.contains(item, e.target);
                    if (!tag) {
                        $(item).find('.zd-selecttree-option-content').stop().slideUp();
                    }
                })

            })
            this.$element.find('.zd-selecttree-checked-content').unbind("click").click(function (e) {
                _this.$element.find('.zd-selecttree-option-content').stop().slideToggle();
            });
            this.$element.find('.zd-selecttree-option-item').unbind("click").click(function (e) {
                //更新选中数据
                var obj = {};
                obj.id = $(this).attr('_id');
                obj.name = $(this).attr('_name');
                obj._parentId = $(this).attr('__parentId');

                //点击选项时,修改选中颜色
                if (_this.options.multiple) {//如果支持多选
                    if ($(this).children('.zdselecttree-select-icon').hasClass('zdselecttree-select-icon-active')) {
                        $(this).children('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active')
                        _this.unselectCb(obj);
                    } else {
                        $(this).children('.zdselecttree-select-icon').addClass('zdselecttree-select-icon-active')
                        _this.selectCb(obj);
                    }
                } else {//如果只支持单选
                    if ($(this).children('.zdselecttree-select-icon').hasClass('zdselecttree-select-icon-active')) {
                        $(this).children('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active')
                        _this.unselectCb(obj);
                    } else {
                        _this.$element.find('.zdselecttree-select-icon').removeClass('zdselecttree-select-icon-active')
                        $(this).children('.zdselecttree-select-icon').addClass('zdselecttree-select-icon-active')
                        _this.selectCb(obj);
                    }
                }

                return false;
            });
            this.$element.find('.root-nochild').click(function () {
                return false;
            })
            this.$element.find('.nochild').click(function () {
                return false;
            })
            this.$element.find('.selecttree-row-deploy').not('.root-nochild').not('.nochild').unbind("click").click(function (e) {
                if ($(this).hasClass('row-close')) {
                    $(this).removeClass('row-close').addClass('row-open');
                    var rowid = $(this).parent().parent().attr('row-id');

                } else if ($(this).hasClass('row-open')) {//关闭子列表逻辑
                    $(this).removeClass('row-open').addClass('row-close');
                    var rowid = $(this).parent().parent().attr('row-id');

                } else if ($(this).hasClass('child-row-close')) {
                    $(this).removeClass('child-row-close').addClass('child-row-open');
                    var rowid = $(this).parent().parent().attr('row-id');

                } else if ($(this).hasClass('child-row-open')) {//关闭子列表逻辑
                    $(this).removeClass('child-row-open').addClass('child-row-close');
                    var rowid = $(this).parent().parent().attr('row-id');

                }
                if ($(this).siblings(".zd-selecttree-option-list").hasClass('hide-options')) {
                    $(this).siblings(".zd-selecttree-option-list").removeClass('hide-options').addClass('show-options')
                } else {
                    $(this).siblings(".zd-selecttree-option-list").removeClass('show-options').addClass('hide-options')
                }
                return false;
            })
            this.setSelectData(this.options.defaultSelect)
            return this;
        },
        createOptionList: function (item) {
            var _this = this;
            if(item.selected){
                _this.options.defaultSelect.push(item.id)
            }
            var gradeclass = '';
            if (item.childList && item.childList.length == 0) {
                if (item.level == 1) {
                    gradeclass = 'root-nochild';
                    if (item.childList && item.childList.length != 0) {
                        gradeclass += ' row-close'
                    } else {
                        gradeclass += ' row-open'

                    }
                } else {
                    gradeclass = 'nochild';
                    if (item.childList && item.childList.length != 0) {
                        gradeclass += ' child-row-close'
                    } else {
                        gradeclass += ' child-row-open'

                    }
                }
            }
            var marginLeft = item.level * 30 - 56;
            var paddingLeft = marginLeft + 40;
            var str = "<li class='zd-selecttree-option-item' _id=" + item.id + " _name=" + item.name + " _parentid=" + item.parentId + ">";
            if (item.level == 1) {
                str += "<span style='margin-left:" + 0 + "px' class='selecttree-row-deploy " + gradeclass + " row-close'></span>";
                str += "<span style='padding-left: 24px;'>" + item.name + "</span>";
                str += "<span class='zdselecttree-select-icon'>✔</span>";
            } else {
                str += "<span style='margin-left:" + marginLeft + "px' class='selecttree-row-deploy " + gradeclass + " child-row-close'></span>";
                str += "<span style='padding-left:" + paddingLeft + "px'>" + item.name + "</span>";
                str += "<span class='zdselecttree-select-icon'>✔</span>";
            }
            if (item.childList && item.childList.length != 0) {
                str += "<ul class='zd-selecttree-option-list hide-options'>";
                $.each(item.childList, function (index, item) {
                    str += _this.createOptionList(item);
                })
                str += '</ul>';
            }
            str += '</li>';
            return str;
        },
        init: function () {
            var _this = this;
            this.$element.css({ 'height': '35px', 'display': 'inline-block' })
            var optionsList = this.options.data;
            var methodStyle = 'max-height:' + this.options.maxHeight + 'px';
            if (_this.options.position == 'bottom') {
                var str = "<div class='zd-selecttree-content'><div class='zd-selecttree-checked-content'><span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span></div><div class='zd-selecttree-option-content zd-selecttree-option-content-bottom' style=" + methodStyle + "><ul class='zd-selecttree-option-list show-options'>";
            } else {
                var str = "<div class='zd-selecttree-content'><div class='zd-selecttree-checked-content'><span class='zdselecttree-placeholder'>" + _this.options.placeholder + "</span></div><div class='zd-selecttree-option-content zd-selecttree-option-content-top' style=" + methodStyle + "><ul class='zd-selecttree-option-list show-options'>";
            }
            for (var i = 0; i < optionsList.length; i++) { //循环添加行
                str += _this.createOptionList(optionsList[i]);
            }
            str += "</ul></div></div></div>"
            this.$element.html(str);
            return this.bindEvent();
        }
    }
    //在插件中使用zdSelectTree对象
    $.fn.zdSelectTree = function (options) {
        //创建zdSelectTree的实体
        var zdSelectTree = new ZdSelectTree(this, options);
        //调用其方法
        return zdSelectTree.init();
    }
})(jQuery, window, document);

css

ul li{
    list-style: none;
}
.zd-selecttree-content{
    position: relative;
}
.zd-selecttree-checked-content{
    position: absolute;
    top: 0px;
    width: 100%;
    height: 30px;
    border: 1px solid #f1f1f1;
    border-radius: 4px;
    line-height: 30px;
    font-size: 14px;
    z-index: 0;
    padding-left: 10px;
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-right: 30px;
}
.zd-selecttree-option-content{
    position: absolute;
    border: 1px solid #f3f3f3;
    width: 100%;
    display: none;
    border-radius: 4px;
    overflow-y: auto;
    background: #fff;
    z-index: 999;
}
.zd-selecttree-option-content-top{
    bottom: 2px;
}
.zd-selecttree-option-content-bottom{
    top: 35px;
}
.zd-selecttree-content ul{
    padding: 0;
    margin: 0;
}
.zd-selecttree-content ul li{
    list-style: none;
    cursor: pointer;
    clear: both;
}
.zd-selecttree-content .root-nochild {
    width: 10px;
    height: 10px;
    background-image: url("./images/show.png");
    background-repeat: no-repeat;
    background-size: contain;
    display: inline-block;
    margin-top: 9px;
}
.selecttree-content{
    width: 100%;
    border-collapse: collapse;
}
.selecttree-content tr th{
    font-size: 14px;
    color: #666666;
    font-weight: 400;
    padding: 12px;
    box-sizing: border-box;
    background-color: #FFF8F0;
}
.selecttree-content tr td{
    font-size: 12px;
    color: #666666;
    padding: 12px;
    position: relative;
}
.selecttree-content,.selecttree-content tr th,.selecttree-content tr td { border:1px solid #F1F1F1; }
.selecttree-btn{
    padding: 6px 12px;
    border: 1px solid #f1f1f1;
    border-radius: 4px;
    box-sizing: border-box;
    cursor: pointer;
}
.selecttree-row-deploy{
    display: inline-block;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
    left: 6px;
}
.selecttree-row-grade-0{
    display: inline-block;
    position: absolute;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-size: contain;
    left: 0;
    margin-left: 20px;
}
.zd-selecttree-content .row-close{
    width: 10px;
    height: 10px;
    background-image: url("./images/hide.png");
    background-repeat: no-repeat;
    background-size: contain;
    margin-top: 9px;
}
.zd-selecttree-content .row-open{
    width: 10px;
    height: 10px;
    background-image: url("./images/show.png");
    background-repeat: no-repeat;
    background-size: contain;
    margin-top: 9px;
}
.zd-selecttree-content .child-row-close{
    width: 30px;
    height: 10px;
    background-image: url("./images/haschild-close.png");
    background-repeat: no-repeat;
    background-size: contain;
    margin-top: 9px;
}
.zd-selecttree-content .child-row-open{
    width: 30px;
    height: 10px;
    background-image: url("./images/haschild-open.png");
    background-repeat: no-repeat;
    background-size: contain;
    margin-top: 9px;
}
.show-row{
    display: block;
}
.hide-row{
    display: none;
}
.root-nochild{
    width: 10px;
    height: 10px;
    background-image: url("./images/show.png");
    background-repeat: no-repeat;
    background-size: contain;
}
.nochild{
    width: 30px;
    height: 10px;
    background-image: url("./images/haschild-open.png");
    background-repeat: no-repeat;
    background-size: contain;
}
.hide-options{
    display: none;
}
.show-options{
    display: block;
}
.zdselecttree-select-icon{
    float: right;
    color: #fff;
}
.zdselecttree-select-icon-active{
    color: #666;
}
.clear-both{
    clear: both;
}
.zdselecttree-placeholder{
    color: #666;
}
.zd-selecttree-checked-content:after {
    position: absolute;
    right: 12px;
    top: 12px;
    display: inline-block;
    content: '';
    width: 0;
    height: 0;
    border: 6px solid #000;
    border-bottom-color: transparent;
    border-left-color: transparent;
    border-right-color: transparent;
}
.zd-selecttree-option-item span{
    height: 28px;
    line-height: 28px;
    display: inline-block;
}

html demo

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="zdSelectTree.css">
    <title>Document</title>
    <style>
        .selecttree{
            width: 232px;
            height: 35px;
            margin-top:140px;
        }
    </style>
</head>

<body>
    <div class="selecttree" id="selecttree">1
    </div>
    <div class="selecttree" id="selecttree2">2
    </div>
    <div class="selecttree" id="selecttree3">3
    </div>
    <script src="../../libs/jquery-1.10.2.min.js"></script>
    <script src="zdSelectTree.js"></script>
    <script>
        function changeCb(a,b){
            console.log(a)
            console.log(b)
        }
        var config = {
            changeCb:changeCb,
            data: [
                {
                    "id": "1807261600020010010000000",
                    "parentId": "0000-0000",
                    "name": "啦啦啦啦啦啦",
                    "level": 1,
                    "isSelect": false,
                    "childList": []
                },
                {
                    "id": "1807301010420010010000000",
                    "parentId": "0000-0000",
                    "name": "测试",
                    "level": 1,
                    "isSelect": false,
                    "childList": []
                },
                {
                    "id": "1808071709510010010000000",
                    "parentId": "0000-0000",
                    "name": "单",
                    "level": 1,
                    "isSelect": false,
                    "childList": [
                        {
                            "id": "1808071710430010010000000",
                            "parentId": "1808071709510010010000000",
                            "name": "单单",
                            "level": 2,
                            "isSelect": false,
                            "childList": [
                                {
                                    "id": "1808071711190010010000000",
                                    "parentId": "1808071710430010010000000",
                                    "name": "单单单",
                                    "level": 3,
                                    "isSelect": false,
                                    "childList": []
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "222",
                    "parentId": "0000-0000",
                    "name": "bbbb",
                    "level": 1,
                    "isSelect": false,
                    "childList": []
                },
                {
                    "id": "333",
                    "parentId": "0000-0000",
                    "name": "patent-cccc",
                    "level": 1,
                    "isSelect": false,
                    "childList": []
                },
                {
                    "id": "1808071333520010010000000",
                    "parentId": "0000-0000",
                    "name": "aaa",
                    "level": 1,
                    "isSelect": false,
                    "childList": []
                },
                {
                    "id": "1807251452470010010000000",
                    "parentId": "0000-0000",
                    "name": "类别添加",
                    "level": 1,
                    "isSelect": false,
                    "childList": [
                        {
                            "id": "1807251538060010010000000",
                            "parentId": "1807251452470010010000000",
                            "name": "类别2",
                            "level": 2,
                            "isSelect": false,
                            "childList": [
                                {
                                    "id": "1807261503260010010000000",
                                    "parentId": "1807251538060010010000000",
                                    "name": "修改的",
                                    "level": 3,
                                    "isSelect": false,
                                    "childList": []
                                }
                            ]
                        }
                    ]
                }
            ]
        }
        var selecttree = $('#selecttree').zdSelectTree(config)
        var selecttree2 = $('#selecttree2').zdSelectTree(config)
        var selecttree3 = $('#selecttree3').zdSelectTree(config)
        selecttree.setSelectData(['1807301010420010010000000','1808071711190010010000000','1808071710430010010000000']);
        
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_27223987/article/details/81941298