jquery实现下拉多选框

3次阅读

共计 1530 个字符,预计需要花费 4 分钟才能阅读完成。

最近公司有个老项目需要加一些新功能,老项目是用 jquery 开发的,现在要做一个下拉多选框,找了很多原生的 UI 插件都没有下拉多选框或者就是原生需要加 ctrl 才可以多选,这里用 ul li 做的下拉多选框下面放代码:
html 代码:

<div class="divBox">
    <div class="duiMutiple">
      <div class="divSel"> 多选选择 </div>
      <ul id="usertype">
              <li value="1"> 吃饭 </li>
        <li value="2"> 睡觉 </li>
        <li value="3"> 玩手机 </li>
      </ul>
    </div>
  </div>

javaScript 代码(记得引入 jquery.js 文件)

let setValList = [],setLabelList = [];
        //select 多选
        $("#usertype").hide();
        $(".divSel").click(function() {$("#usertype").toggle();});
        $('#usertype li').click(function () {if(setValList.indexOf($(this).val()) === -1){setValList.push($(this).val());
                setLabelList.push($(this).text());
                $(this).addClass('optionSelStyle');
            }else {let index = setValList.indexOf($(this).val());
                setValList.splice(index,1);
                setLabelList.splice(index,1);
                $(this).removeClass('optionSelStyle');
            }
            console.log(setLabelList) // 选择的多选框中的数据
            $('.divSel').html(setLabelList.join(' '));
        })

css 代码:

.duiMutiple{
      width: 120px;
      height: 24px;
      position: relative;
      margin-top: 7px;
      display: block;
      .divSel{
        width: 93px;
        height: 24px;
        line-height: 24px;
        padding-left: 10px;
        cursor: pointer;
        background: #fff;
        border: 1px solid #95b7e7;
        position: absolute;
        top: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      #usertype{
        width:120px;
        max-height:200px;
        border-radius:5px;
        background: #fff;
        border:1px solid #95b7e7;
        overflow: auto;
        margin-top: -20px;
        display: none;
        z-index: 99999!important;
        position: absolute;
        top: 48px;
        li{
          width: 90px;
          height: 30px;
          line-height: 30px;
          padding: 0 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          float: left;
        }
      }
      .optionSelStyle{
        background: #3188E1;
        color: #fff;
      }
    }
正文完
 0