封装下拉框插件

652 阅读2分钟

简单封装的一个下拉框插件,只做了简单的样式处理,主要实现下拉功能,依赖Jquery,

使用: 首先引入该插件,插件会在window上挂在select方法,用法select(dom,options,callback)

  1. dom是需要作为下拉框的父元素

  2. option配置 有以下几个属性

         *1      chooseTips 要显示提示语,例如请选择任务
         *2      defaultVal 默认选中的key值
         *3      titleKey   数组中用于显示的属性值
         *4      valueKey   数组中用于选中的 value值
         *5      list       传入的数组,对应多少个下拉框
    

3.callback回调函数 返回两个参数 第一个参数是当前选中的valueKey值,第二个参数是当前选中的这个数组中的对象

4.方法执行 返回一个对象,对象上提供两个方法

 1.changeList  改变显示的下拉框数组  传入一个新数组,注意该数组的titleKey和valueKey要和以前的一样
 2.setValue    改变当前选中项目,传入当前数组中的valueKey值
 

使用方法如下,

    <div class="box" style="width:250px;height:70px;"></div>
    
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script src="../test/select.js"></script>
    <script>
    	let arr = [{
                      name: '选项一',
                      id: 1
                  },{
                      name: '选项二',
                      id: 2
                  },{
                      name: '选项三',
                      id: 3
                  }]
         let selectObj1 = select('.box',{
         	chooseTips:'请选择选项',
                defaultVal:2,//可不传,现在代表默认选中选项二
                titleKey:'name',
                valueKey:'id',
                list:arr,
         },function(val,obj){
         	//选中一个选项后触发回调,返回val为当前选中的valueKey值,obj为当前选中这个数组中的对象
            console.log(val,obj)
         })
    </script>

    (function() {
        /**
         * 1. dom是需要作为下拉框的父元素
         * 2. option配置 有以下几个属性
         *      chooseTips 要显示提示语,例如请选择任务 不传则默认为‘请选择选项’
         *      defaultVal 默认选中的key值
         *      titleKey   数组中用于显示的属性值
         *      valueKey   数组中用于选中的 value值
         *      list       传入的数组,对应多少个下拉框
         * 3.callback回调函数 返回两个参数 第一个参数是当前选中的valueKey值,第二个参数是当前选中的这个数组中的对象
         * 
         * 整个方法执行 返回一个对象,对象上提供两个方法
         *       1.changeList  改变显示的下拉框数组  传入一个新数组,注意该数组的titleKey和valueKey要和以前的一样
         *       2.setValue    改变当前选中项目,传入当前数组中的valueKey值
         */
        function select(dom, option, callback) {
            let list = JSON.parse(JSON.stringify(option.list)); //传入的数组,对应多少个下拉框
            let chooseTips = option.chooseTips; //要显示提示语,例如请选择任务
            let defaultVal = option.defaultVal; //默认选中的key值
            let titleKey = option.titleKey //数组中用于显示的属性值
            let valueKey = option.valueKey //数组中用于选中的 value值
            let height = $(dom).height();
            let width = $(dom).width();
            list.unshift({
                [titleKey]: chooseTips || '请选择选项',
                [valueKey]: ''
            })
            let str1 = `<div class="showDiv" data-val="" style="width:100%;height:100%;">${chooseTips || '请选择选项'}</div>`
            str1 += `<div class="content" style="top:${height}px;">`
            list.forEach((item, i) => {
                str1 += ` <div class="select_item" style="width:${width}px;height:${height}px;" data-val="${item[valueKey]}">${item[titleKey]}</div>`
            });
            str1 += ` </div>`
            $(dom).append(str1);
            event()

            if (defaultVal) {
                $(dom).find('.select_item').each((i, item) => {
                    if ($(item).attr('data-val') == defaultVal) {
                        $(item).click()
                    }
                })
            }
            this.changeList = function changeList(newlist) {
                if (newlist[titleKey] == null || newlist[valueKey]) throw new Error('key and value must be same of last time')
                $(dom).children().remove()
                list = JSON.parse(JSON.stringify(newlist));;
                list.unshift({
                    [titleKey]: chooseTips || '请选择选项',
                    [valueKey]: ''
                })
                let str1 = `<div class="showDiv" data-val="" style="width:100%;height:100%;">${chooseTips || '请选择选项'}</div>`
                str1 += `<div class="content" style="top:${height}px;">`
                list.forEach((item, i) => {
                    str1 += ` <div class="select_item" style="width:${width}px;height:${height}px;" data-val="${item[valueKey]}">${item[titleKey]}</div>`
                });
                str1 += ` </div>`
                $(dom).append(str1);
                event()
            }
            this.setValue = function setValue(val) {
                $(dom).find('.select_item').each((i, item) => {
                    if ($(item).attr('data-val') == val) {
                        $(item).click()
                    }
                })
            }

            function event() {
                $(dom).find('.showDiv').on('click', function() {
                    if ($(dom).find('.content').hasClass('active')) {
                        $(dom).find('.content').removeClass('active').hide()
                    } else {
                        $($(dom).find('.content').children('.select_item').get(0)).show()

                        if (!$(this).attr('data-val') && list.length > 1) {
                            $($(dom).find('.content').children('.select_item').get(0)).hide()
                        }

                        $(dom).find('.content').addClass('active').show()
                    }
                })
                $(dom).find('.select_item').on('click', function() {

                    let html = $(this).html()
                    let val = $(this).attr('data-val')
                    $(dom).find('.showDiv').html(html).attr('data-val', val);
                    $(dom).find('.content').hide().removeClass('active');
                    let obj = list.find(item => item[valueKey] == val)
                    callback && callback(val, obj)
                })

            }
        }

        function temp(dom, option, callback) {
            return new select(dom, option, callback)
        }

        window.select = temp
    })()
	
    对应的 css
     <style>
        * {
            margin: 0;
            padding: 0;
        }

        .boxstyle {
            margin-left: 20px;
            position: relative;
            width: 200px;
            height: 30px;
            border: 1px solid #ccc;
            box-sizing: border-box;
            cursor: pointer;
        }

        .showDiv {
            width: 100%;
            height: 100%;
            padding-left: 4px;
        }

        .content {
            display: none;
            position: absolute;
            left: -1px;
            /* top: 29px; */
            width: 100%;
            max-height: 150px;
            overflow-y: auto;
            /* border: 1px solid #ccc; */
            z-index: 666;
            background-color: #fff;
            border-bottom: 1px solid #ccc;
        }

        .content::-webkit-scrollbar {
            display: none;
        }

        .select_item {
            /* margin-top: -1px; */
            /* margin-left: -1px; */
            /* width: 250px;
            height: 30px; */
            border: 1px solid #ccc;
            padding-left: 4px;
            box-sizing: border-box;
            cursor: pointer;
        }

        .select_item:hover {
            border: 0.5px solid blue;
        }
</style>