首页 > 代码库 > jQuery实现简单的下拉可输入组合框

jQuery实现简单的下拉可输入组合框

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

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

CSS code:
1
.container{ 2 margin: 20px auto; 3 padding:0 15px; 4 width: 50%; 5 height:300px; 6 box-sizing: border-box; 7 } 8 .text-container{ 9 display: inline-block; 10 float:left; 11 width: 15%; 12 height: 32px; 13 line-height: 32px; 14 box-sizing: border-box; 15 } 16 .selectContainer{ 17 width: 70%; 18 height:200px; 19 float:left; 20 position: relative; 21 padding:0; 22 margin:0; 23 box-sizing: border-box; 24 } 25 .selectedContent{ 26 width:85%; 27 height: 25px; 28 float:left; 29 } 30 .dropDown-toggle{ 31 width:14%; 32 height:31px; 33 line-height: 31px; 34 text-align: center; 35 border: 1px solid silver; 36 border-left:none; 37 float:left; 38 padding:0; 39 margin:0; 40 box-sizing: border-box; 41 cursor: pointer; 42 } 43 .dropDown-menu{ 44 margin:0; 45 padding:0 15px 10px; 46 width:100%; 47 border:1px solid silver; 48 border-top: none; 49 box-sizing: border-box; 50 list-style: none; 51 position: absolute; 52 top:31px; 53 right:0; 54 } 55 .items{ 56 margin-top:8px; 57 padding: 2px; 58 cursor: pointer; 59 } 60 .items:hover{ 61 background: #ddd; 62 } 63 .dsn{ 64 display: none; 65 }
Html code:
1
<div class="container"> 2 <span class="text-container">最爱的水果:</span> 3 <div class="singleSelect selectContainer"> 4 <input type="text" class="selectedContent"> 5 <div class="dropDown-toggle">选择</div> 6 <ul class="dropDown-menu dsn"> 7 <li class="items">苹果</li> 8 <li class="items"></li> 9 <li class="items">橘子</li> 10 </ul> 11 </div> 12 </div>
JavaScript code: 
1
$(‘.items‘).on(‘click‘, function(){ 2 if($(this).parents(‘.selectContainer‘).hasClass(‘singleSelect‘)){ 3 $(this).parents(‘.selectContainer‘).find(‘.selectedContent‘).val($(this).text()); 4 $(this).parent().addClass(‘dsn‘); 5 } 6 }); 7 $(‘.dropDown-toggle‘).on(‘click‘, function(){ 8 $(this).next().toggleClass(‘dsn‘); 9 });

本文中使用Jquery-2.1.1完成,请多多指教。

jQuery实现简单的下拉可输入组合框