工欲善其事, 必先利其器
对于很多非专业前端开发来说写页面是非常痛苦的, 借助框架或插件往往能够达到事半功倍的效果, 本系列文章会介绍我在运维系统开发过程中用到的那些顺手的前端插件, 如果你是想写 XX 管理系统的学生, 或是需要独自做 Dashboard 的后端工程师, 亦或是像我这样半吊子的开发加运维, 那么这个系列的文章你一定不要错过
Bootstrap Dual Listbox 是一款基于 Bootstrap 的双向 select 选择框控件, 作为对 multiple select 的扩展, 使用起来非常简单, 功能也更强大
项目 GitHub 地址:
基本使用
需要用到的 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://www.cnblogs.com/37Y37/p/11229806.html