jQuery:sumoselect 插件实现select下拉复选框

主页:http://hemantnegi.github.io/jquery.sumoselect/

项目:https://github.com/HemantNegi/jquery.sumoselect

下载:jquery.sumoselect-master

DEMO: http://hemantnegi.github.io/jquery.sumoselect/sumoselect_demo.html

简单介绍

jquery.sumoselect是一款跨设备、跨浏览器的jQuery下拉列表框插件。该jQuery下拉列表框插件可以单选,也可以多选。它的样式可以通过CSS文件来自定义。它的最大特点是可以跨设备使用,所有设备上功能都是一致的。

该jQuery下拉列表框插件的特点有:

  • 可以进行单选,也可以进行多选。
  • 可以通过CSS文件来自定义样式。
  • 支持绝大多数的设备。
  • 根据设备智能渲染。
  • 在Android、IOS、Windows和其它设备上会自动渲染出该设备原生样式的下拉列表框。
  • 可以自定义提交数据的格式(多选可以通过 csv 或默认形式来提交)。
  • 支持Selected、Disabled和占位文本。
  • 易扩展,开发者可以很容易的创建新的组件。
  • 使用基本方法间隙管理如添加选项、删除选项、禁用、选择等。

该jQuery下拉列表框插件需要使用jQuery 1.8.3+版本,建议使用最新版本的jQuery。

浏览器和设备的支持

  • IE8+, Firefox 4+, Chrome, Safari 4+, Opera 11+(其它浏览器应该也能工作,但未经测试)
  • iOs 3+, Android 2.1+ , Windows Mobile(其它设备应该也可以工作,但未经测试)

使用方法

首先调入必要文件

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="jquery.sumoselect.min.js"><script>
<link href="sumoselect.css" rel="stylesheet" />

使用方法非常简单,可以在页面加载之后调用默认的调用方法:

$(document).ready(function () {
      $('.SlectBox').SumoSelect();
});

也可以使用插件提供的参数来进行控制:

$(document).ready(function () {
  $('.SlectBox').SumoSelect({
    placeholder: 'This is a placeholder',
    csvDispCount: 3
  });
});

配置参数

下面是该jQuery下拉列表框插件的可用参数:

参数 类型 描述
placeholder string 显示在select下拉列表框中的占位文本
csvDispCount int 要显示的多个项的编号,使用逗号分隔。设置为0表示全选
captionFormat string 当选择的项大于csvDispCount设置的数目时显示的文本。默认为{0} Selected{0}会被替换为选择的项的总数
floatWidth int 最小的设备宽度,如果小于这个宽度,下拉列表框将渲染为浮动弹出的效果
forceCustomRendering boolean Force the custom modal ( Floating list ) on all devices below floatWidth resolution.
nativeOnDevice Array[string] 从用户代理字符串中获取识别移动手机的关键字
outputAsCSV boolean 设置为true则使用csv来提交数据
csvSepChar string 如果outputAsCSV设置为true,该选项用作它的分割符。
okCancelInMulti boolean 在桌面模式中是否允许OK/Cancel按钮为多选模式。
triggerChangeCombined boolean In Multiselect mode whether to trigger change event on individual selection of each item or on combined selection ( pressing of OK or Cancel button ).
selectAll boolean 默认为false,在多选模式下是否显示全选按钮,官方js里说手机模式下不支持全选
selectAlltext string 全选按钮显示模式下全选的显示文本
ok string 默认为OK,确认按钮显示文本
cancel string 默认为Cancel,取消按钮显示文本

(以上基本为网页搜索结果)

官网配置:

Option Type Discription
placeholder (string) The palceholder text to be displayed in the rendered select widget (on priority basis). *Maximum priority is given to native placeholder attribute in select tag i.e. – <select placeholder="this is a placeholder" /> – Then the option with disabled and selected attribute i.e. <option disabled selected value="foo" > – Last to to the given placeholder attribute in the settings. *
csvDispCount (int) The number of items to be displayed in the widget seperated by a , after that the text will be warped as 3+ Selected. Set 0 for all the options.
captionFormat (string) Its the format in which you want to see the caption when more than csvDispCount items are selected. its default value is'{0} Selected' ( here {0} will be replaced by the seletion count )
captionFormatAllSelected (string) I Format of caption text when all elements are selected. set null to use captionFormat. It will not work if there are disabled elements in select. default is '{0} all selected!'
floatWidth (int) Minimum screen width of device below which the options list is rendered in floating popup fashion.
forceCustomRendering (boolean)  Force the custom modal ( Floating list ) on all devices below floatWidth resolution.
nativeOnDevice (Array[string]) The keywords to identify a mobile device from useragent string. The system default select list is rendered on the matched device.
outputAsCSV (boolean) true to POST data as csv ( false for deafault select )
csvSepChar (string) Seperation char if outputAsCSV is set to true
okCancelInMulti (boolean) Displays Ok Cancel buttons in desktop mode multiselect also.
isClickAwayOk (boolean) for okCancelInMulti=true. sets whether click outside will trigger Ok or Cancel (default is cancel).
triggerChangeCombined (boolean) In Multiselect mode whether to trigger change event on individual selection of each item or on combined selection ( pressing of OK or Cancel button ).
selectAll (boolean) To display select all check or not
search (boolean) To enable searching in sumoselect (default is false).
searchText (string) placeholder for search input.
noMatch (string) placeholder to display if no itmes matches the search term (default ‘No matches for “{0}”‘).
prefix (string) prefix to prepend the selected text (default is empty) eg. ‘<b>Hello</b>’.
locale (array) change the text used in plugin ([‘OK’, ‘Cancel’, ‘Select All’]). Note: don’t break the sequence or skip items.
up (boolean) the direction in which to open the dropdown (default: false)
showTitle (boolean) set to false to prevent title (tooltip) from appearing (deafult: true)

默认设置:

{
    placeholder: 'Select Here',
    csvDispCount: 3,
    captionFormat: '{0} Selected',
    captionFormatAllSelected: ''{0} all selected!'',
    floatWidth: 500,
    forceCustomRendering: false,
    nativeOnDevice: ['Android', 'BlackBerry', 'iPhone', 'iPad', 'iPod', 'Opera Mini', 'IEMobile', 'Silk'],
    outputAsCSV : false,
    csvSepChar : ',', 
    okCancelInMulti: true, 
    isClickAwayOk: false,
    triggerChangeCombined : true,
    selectAll : false,
    search : false,
    searchText : 'Search...',
    noMatch : 'No matches for "{0}"',
    prefix : '',
    locale :  ['OK', 'Cancel', 'Select All'],
    up : 'false',
    showTitle : 'true',
}

参数的控制最好在页面中进行,而非在js文件中直接更改,但是因人而异。

官方提供的sumoselect插件,通过参数的调整,在桌面模式下效果还是很不错的,可以选择是否显示确定、取消按钮,根据需求设置下拉框浮动的最小宽度(floadWidth)等等,但是在手机模式下,效果就不是很理想。作为一名开发者,在软件操作方面一般不会觉得太复杂,而在用户角度则可能不然。例如官方提供的sumoselect插件在手机模式下使用的是手机自带的select效果。在多选模式下,往往会造成用户选择了多个items后,不知道该怎么操作了。如果在手机多选模式下也能像桌面模式那样可以设置确定取消按钮的显隐的话,效果会更好些。针对这一需求,我对sumoselect.js文件和sumoselect.css文件进行了修改。最终呈现效果如下

jQuery:sumoselect 插件实现select下拉复选框
jQuery:sumoselect 插件实现select下拉复选框

手机模式下,跟桌面模式显示的一样,不同的是,在手机模式下浮动的话,增加了一个遮罩层,使效果更好些。

前台设置如下

$(function() {
    //初始化下拉框组件
    window.asd = $('#zone').SumoSelect({ 
        placeholder:"请选择",
        csvDispCount: 10,
        captionFormat:'选中 {0} 项',
        floatWidth:1200,//手机端均呈现浮动效果
        okCancelInMulti:true,
        ok:'确定',
        cancel:'取消',
        nativeOnDevice: ['Android', 'BlackBerry', 'iPhone', 'iPad', 'iPod', 'Opera Mini', 'IEMobile', 'Silk']
});

具体详见js文件和css文件。

需要注意的是,由于下拉框的结构是ul li结构,所以如果外层也设置了针对ul li的行高等显示属性的话,就会造成显示效果不尽人意。

items选择非选择的显示效果如上图,左边小方框是利用i元素,为其设置background实现的。

请参照如下代码

<style type="text/css">
        //设置行高
    .SumoSelect > .optWrapper.multiple > .options > li{
        line-height: 18px;
        height:18px;
    }
        //设置确定取消按钮的行高
    .SumoSelect > .optWrapper.multiple.okCancelInMulti > .MultiControls > p{
        line-height: 18px;
    }
        //选择框未选择时的背景设置
    .SumoSelect > .optWrapper.multiple > .options > li span i{
        background-image: none;
        background-size:auto;
    }
</style>

上述代码主要针对外层的css属性设置影响了下拉框的显示效果,为恢复默认显示效果进行的设置。如果要自定义行高等属性,请考虑items本身的padding/margin等属性的设置。

事件处理

$('select.SlectBox').on('sumo:opened', function(sumo) {
    // Do stuff here
    console.log("Drop down opened", sumo)
});
//sumo:opening //Drop down opening
//sumo:opened //Drop down opened
//sumo:closing //Drop down closing
//sumo:closed //Drop down closed.

Methods

To call below functions you need to get the instance of SumoSelect object which can be done as

 var MySelect;
$(document).ready(function () {
            MySelect = $('.SlectBox').SumoSelect();
     });

Or simply you can get the instance from select element directly i.e.

 var MySelect = $('select.SlectBox')[0].sumo;

Note : The SumoSelect object is directly binded with native select element not with the jquery object of element.

Following is the list of methods of SumoSelect.

  • .unload()Deactivate the SumoSelect plugin and display original select element. ( You can reinitialize the SumoSelect for this select. )
     $('select.SlectBox')[0].sumo.unload();
  • .add(value [,text][,index])Insert an new item in the select at a given index if index is provided else added to last. use index 0 to insert at the begining.
    // adds a option with value and html set to 'india' at the last.
    $('select.SlectBox')[0].sumo.add('india');
    
    // adds a option with value and html set to 'india' at index no 3.
    $('select.SlectBox')[0].sumo.add('india',3);
    
    // adds a option with value = 'india' and html = 'Indian' at the last.
    $('select.SlectBox')[0].sumo.add('india','Indian');
    
    // adds a option with value and html set to 'india' at index no 0.
    $('select.SlectBox')[0].sumo.add('india','Indian',0);
  • .remove(index)Removes an item from a given index number.
     $('select.SlectBox')[0].sumo.remove(2);
  • .selectItem(index/value)Selects (check an item) an item in the list by index or by its value. You can select multiple items in case of a multiselect.
    //selects the item at index 2
     $('select.SlectBox')[0].sumo.selectItem(2);
     //selects the item having value "volo"
     $('select.SlectBox')[0].sumo.selectItem('volo');
  • .unSelectItem(index/value)unselect (uncheck an item) an item in list by index or by value
    //unselects the item at index 2
     $('select.SlectBox')[0].sumo.unSelectItem(2);
     //unselects the item having value "volvo"
     $('select.SlectBox')[0].sumo.unSelectItem('volvo');
  • .disableItem(index)Disables and item in the list
    //disables the item at index 2
     $('select.SlectBox')[0].sumo.disableItem(2);
  • .enableItem(index)Enables and item in the list
    //enables the item at index 2
     $('select.SlectBox')[0].sumo.enableItem(2);
  • .selectAll()Selects all items list
    //selects all items (excluding disabled)
     $('select.SlectBox')[0].sumo.selectAll();
  • .unSelectAll()Un selects all items in the list
    //Un select all items
     $('select.SlectBox')[0].sumo.unSelectAll();
  • .enable()Enables the SumoSelect control
    $('select.SlectBox')[0].sumo.enable();
  • .disable()Disable the SumoSelect control
    $('select.SlectBox')[0].sumo.disable();
  • .unSelectAll()Un selects all items in the list
    //Un select all items
    $('select.SlectBox')[0].sumo.unSelectAll();
  • .reload()This method reloads the UI over original select element. so now you can perform the desired operations on underlying select element and then update the UI od sumoselct after that.
    //Reloads the UI of plugin.
    $('select.SlectBox')[0].sumo.reload();

*** You can add custom css class to options (css class added to option is added to the generated li.)

 

本文:jQuery:sumoselect 插件实现select下拉复选框

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.