栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

用jQuery实现可输入多选下拉组合框实例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用jQuery实现可输入多选下拉组合框实例代码

  【写在前面的话】网站上很多用各种插件,比如依赖bootstrap的bootstrap-select插件等。虽然这些框架可以实现很多功能,但因为在实际项目中,可能只会用到其中的某个功能,若是一概引入,会导致整个js加载过于笨重。比如前面提到的bootstrap-select插件,在不压缩的情况下,达到300多k。因此,为了实现一个可填写的下拉框有点得不偿失。

  基于这种原因,于是私下用jquery写了一个比较简单的多选下拉可填写组合框。  

 container{
   margin: 20px auto;
   padding:0 15px;
   width: 50%; 
   height:300px;
   box-sizing: border-box;  
  }
  .text-container{
   display: inline-block;
   float:left;
   width: 15%;
   height: 32px;
   line-height: 32px;
   box-sizing: border-box;
  }
  .selectContainer{
   width: 70%;
   height:200px;
   float:left;
   position: relative;
   padding:0;
   margin:0;
   box-sizing: border-box;
  }
  .selectedContent{
   width:85%;
   height: 25px;
   float:left;   
  }
  .dropDown-toggle{
   width:14%;
   height:31px;
   line-height: 31px;
   text-align: center;
   border: 1px solid silver;
   border-left:none;
   float:left;
   padding:0;
   margin:0;
   box-sizing: border-box;
   cursor: pointer;
  }
  .dropDown-menu{
   margin:0;
   padding:0 15px 10px;
   width:100%;
   border:1px solid silver;
   border-top: none;
   box-sizing: border-box;
   list-style: none;
   position: absolute;
   top:31px;
   right:0;
  }
  .items{
   margin-top:8px;
   padding: 2px;
   cursor: pointer;
  }
  .items:hover{
   background: #ddd;
  }
  .isSelectedText{
   display: inline-block;
   width:90%;
  }
  .dsn{
   display: none;
  }

 最爱的水果
 
  
  选择
  
 
$('.isSelected input[type=checkbox]').on('click', function(){
   var selectedItems = $(this).parents('.dropDown-menu').prevall('.selectedContent').val().split(' ');
   var thisItem = $(this).parent().prev().text();
   var isExisted = 0;
   var isChecked = $(this).is(':checked');
   if(isChecked){
    selectedItems.map(function(item, index){
     if(item === thisItem){
      isExisted++
     }
    });
    if(!isExisted){
     selectedItems.push(thisItem)
    }
   }
   else{
    selectedItems.map(function(item, index){
     if(item === thisItem){
      selectedItems.splice(index, 1);
     }
    });
   }
   $(this).parents('.dropDown-menu').prevall('.selectedContent').val(selectedItems.join(' '));
  })
  $('./confirm/iSelect').on('click', function(){
   $(this).parents('.dropDown-menu').addClass('dsn');
  })
  $('.dropDown-toggle').on('click', function(){
   $(this).next().toggleClass('dsn')
  });

  由于本组件中使用了数组的map方法,可能此方法在ie中不能兼容。由于鄙人电脑ie无法打开,用360浏览器测试后同样可是正常使用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/90784.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号