工欲善其事,必先利其器
對於很多非專業前端開發來說寫頁面是非常痛苦的,借助框架或插件往往能夠達到事半功倍的效果,本系列文章會介紹我在運維系統開發過程中用到的那些順手的前端插件,如果你是想寫XX管理系統的學生、或是需要獨自做Dashboard的后端工程師、亦或是像我這樣半吊子的開發加運維,那么這個系列的文章你一定不要錯過
Bootstrap Dual Listbox是一款基於Bootstrap的雙向select選擇框控件,作為對multiple select的擴展,使用起來非常簡單,功能也更強大
項目Github地址:https://github.com/istvan-ujjmeszaros/bootstrap-duallistbox
基本使用
需要用到的JS和CSS文件位於項目代碼下的dist目錄中,需要將這個目錄中的對應文件放入你的項目里,這一步不贅述
- 引入CSS/JS文件,由於bootstrap-duallistbox是基於bootstrap的,所以要先引入bootstrap相關的css和js
<!-- 加載bootstrap -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- 加載bootstrap-dualllistbox -->
<link rel="stylesheet" href="static/bootstrap-duallistbox/bootstrap-duallistbox.css">
<script src="static/bootstrap-duallistbox/jquery.bootstrap-duallistbox.js"></script>
- 加載duallistbox插件
<select class="form-control" multiple="multiple" name="groups" size="10">
<option value="1">GroupA</option>
<option selected value="2">GroupB</option>
<option value="3">GroupC</option>
<option value="4">GroupD</option>
<option selected value="5">GroupE</option>
<option value="6">GroupF</option>
<option value="7">GroupG</option>
</select>
<script>
var selectorx = $('select[name="groups"]').bootstrapDualListbox();
</script>
- 完成以上兩步可以看到頁面效果如下
非常簡單,到這里已經可以正常使用這個控件了,更多的花樣接着往下看
配置說明
整個界面為英文顯示,有默認提示,如果你想將提示改為中文或添加自定義的提示內容,那么可以通過如下配置
var selectorx = $('select[name="groups"]').bootstrapDualListbox({
nonSelectedListLabel: '未選擇的組',
selectedListLabel: '已選擇的組',
filterTextClear: '展示所有',
filterPlaceHolder: '過濾搜索',
moveSelectedLabel: "添加",
moveAllLabel: '添加所有',
removeSelectedLabel: "移除",
removeAllLabel: '移除所有',
infoText: '共{0}個組',
infoTextFiltered: '搜索到{0}個組 ,共{1}個組',
infoTextEmpty: '列表為空',
});
以上配置都比較簡單,對照中文就能知曉意思,不做過多解釋,另外有幾個支持的參數說明如下:
infoText: 除了設置字符串外還可設置為false
,當設置為false
時可隱藏這段信息
showFilterInputs: 默認為true,是否顯示filter過濾框
moveOnSelect: 默認為true,點擊便會變更選項到對應的選擇框內,如果設置為false則會在出現moveSelected
的箭頭需要點擊箭頭或者雙擊選項后才能變更選項到對應的選擇框
nonSelectedFilter: 未選中的默認過濾規則,可以配置為OPS-COFFEE-A
則未選中的框內只會顯示OPS-COFFEE-A
selectedFilter: 已選中的默認規則,與noSelectedFilter
類似
使用進階
獲取已選擇的值
selectorx.val()
獲取select插件對象
selectorx.bootstrapDualListbox('getContainer')
刷新插件元素用戶界面
selectorx.bootstrapDualListbox('refresh');
刪除bootstrap-duallistbox插件,恢復select原樣
selectorx.bootstrapDualListbox('destroy');
動態添加select的option
selectorx.append('<option value="9" selected>ops-coffee.cn</option>');
selectorx.bootstrapDualListbox('refresh');
注意:上文中的所有selectorx都為加載duallistbox時實例化的select對象
完整Demo
為了方便大家學習,我寫了個完整的demo,你可以在線查看效果或下載代碼應用到自己的項目中
在線Demo地址:https://demo.ops-coffee.cn/duallistbox/
Github源碼地址:https://github.com/ops-coffee/demo/tree/master/duallistbox