在开发颗粒云邮箱的过程中,遇到了一个前端的问题,就是邮箱收件人的那个multiselect的input输入框。不仅能够多选,还要能够支持ajax搜索,把联系人搜索出来。就是类似下面的这个东西:

网上找了很多类似的插件,主要有下面种:

  1. 第一个组件是写bootstrap table的主人公wenzhixin封装的一个组件——multiple-select。这个组件风格简单、文档全、功能强大。但是觉得它选中的效果不太好。关于它的效果展示,我们放在后面。还是给出对应的文档API。

    Multiple-Select源码主页:https://github.com/wenzhixin/multiple-select

    Multiple-Select文档以及Demo:http://wenzhixin.net.cn/p/multiple-select/docs/index.html?locale=zh_CN

  2. 第二个组件也是在github上面找的——bootstrap-multiselect。这个组件风格和第一个非常相似,文档也挺全面。

    bootstrap-multiselect源码主页:https://github.com/davidstutz/bootstrap-multiselect

    bootstrap-multiselect文档以及Demo:http://davidstutz.github.io/bootstrap-multiselect

  3. Jquery的Autocomplete插件:https://github.com/agarzola/jQueryAutocompletePlugin

  4. 一个不怎么为人所知的Jquery插件:marcopolo.js  https://github.com/jstayton/jquery-marcopolo

颗粒云邮箱采用的是上面提到的第四种marcopolo.js来实现多选输入框的。先看看效果图,做得比较丑:

你觉得丑不是因为人家插件的问题,纯属本人的问题……

这个插件的环境要求:

  • jQuery >= 1.4.3

  • jQuery UI Widget >= 1.8.21 (included in minified build)

  • All modern browsers, including IE >= 6

使用该插件你只需要在页面引入如下文件(资源文件自己去github下载,上面给出了地址)

<script src="jquery.min.js"></script>
<script src="jquery.marcopolo.min.js"></script>

然后在HTML代码中添加一个input输入框:

<input type="text" name="userSearch" id="userSearch">

然后加入下面这段JS:

$('#userSearch').marcoPolo({
  url: '/users/search',
  formatItem: function (data, $item) { 
      return data.first_name + ' ' + data.last_name;
  },
  onSelect: function (data, $item) {
      window.location = data.profile_url;
  }
});

上面的url就是你ajax搜索的时候,服务器的响应地址。服务端应该返回json格式的搜索结果:

到这一步,功能上就都是先了,但是其丑无比,你还需要加入下面的CSS来美化一下:

/* Ordered list for displaying selected items. */
div.mf_container ol.mf_list {
    display: inline;
} /* Selected item, regardless of state (highlighted, selected). */
div.mf_container ol.mf_list li.mf_item {
    border: 1px solid #C0C0C0;
    cursor: pointer;
    display: inline-block;
    margin: 2px;
    padding: 4px 4px 5px;
} /* Selected item that's highlighted by mouseover. */
div.mf_container ol.mf_list li.mf_item.mf_highlighted {
    background-color: #E0E0E0;
} /* Selected item that's selected by click or keyboard. */
div.mf_container ol.mf_list li.mf_item.mf_selected {
    background-color: #C0C0C0;
} /* Remove link. */
div.mf_container ol.mf_list li.mf_item a.mf_remove {
    color: #E0E0E0;
    margin-left: 10px;
    text-decoration: none;
} /* Remove link that's highlighted. */
div.mf_container ol.mf_list li.mf_item.mf_highlighted a.mf_remove {
    color: #FFFFFF;
} /* Remove link that's selected. */
div.mf_container ol.mf_list li.mf_item.mf_selected a.mf_remove {
    color: #FFFFFF;
} /* Actual input, styled to be invisible within the container. */
div.mf_container input.mf_input {
    border: 0;
    font: inherit;
    font-size: 100%;
    margin: 2px;
    outline: none;
    padding: 4px;
}

下面附上github上的英文文档,英文好的同学可以完善更多的功能配置:

Options

All options are optional, although url is usually specified unless the input field is in a form by itself (in which case the form'saction attribute can be used).

  • cache boolean

    Whether to cache query results. The cache is shared by all instances, which is a big advantage when many of the same field type appear on the same page. For example, a tags field that's repeated for every record on a page.

    Default: true


  • compare boolean, string

    Whether to compare the selected item against items displayed in the results list. The selected item is highlighted if a match is found, instead of the first item in the list (highlight option must be enabled). Set this option to true if the data is a string; otherwise, specify the data object attribute name to compare on.

    Default: false


  • data object, string, function

    Additional data to be sent in the request query string. (Note: The query string parameter that is set with the input value (param option) will overwrite the value in the data object if an attribute with the same name exists.)

    Default: {}

    When a function is used, it's called for every request, allowing the data to be dynamic. An object must be returned.

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: object of additional data.


    • string Requested input value.

  • delay integer

    The number of milliseconds to delay before firing a request after a change is made to the input value. This helps prevent an ajax request on every keystroke from overwhelming the server and slowing down the page.

    Default: 250


  • hideOnSelect boolean

    Whether to hide the results list when an item is selected. Interesting things can be done when this is set to false, such as hiding and showing certain items when other items are selected. The results list is still hidden when the input is blurred for any other reason.

    Default: true


  • highlight boolean

    Whether to automatically highlight an item when the results list is displayed. Usually it's the first item, but it could be the previously selected item if compare is specified.

    Default: true


  • label selector, jQuery object, DOM element, null

    Positioning a label over an input is a common design pattern (sometimes referred to as overlabel) that unfortunately doesn't work so well with all of the input focus/blur events that occur with autocomplete. With this option, however, the hiding/showing of the label is handled internally to provide a built-in solution to the problem. The label receives the classmp_label.

    Default: null


  • minChars integer

    The minimum number of characters required before a request is fired. See the formatMinChars callback to format the (optional) message displayed when this value is not reached.

    Default: 1


  • param string

    The name of the query string parameter that is set with the input value.

    Default: q


  • required boolean

    Whether to clear the input value when no selection is made from the results list. This happens when the input is blurred, usually by clicking or tabbing out of the field.

    Default: false


  • selectable selector

    The list items to make selectable. For example, say you add the class header to a number of list items (in the formatItemcallback) that you want to act as non-selectable headers. They can be excluded with the selector :not(.header). Selectable items receive the class mp_selectable.

    Default: *


  • selected object, null

    Prime the input with a selected item. onSelect is called just as if the item were selected from the results list.

    Default: null


  • submitOnEnter boolean

    Whether to allow the browser's default behavior of submitting the form on ENTER.

    Default: false


  • url string, null

    The URL to GET request for the results, which must be an array of strings or JSON. If no URL is set, the parent form'saction attribute value is used if one exists. q is added to the query string with the input value, along with any additionaldata.

    Default: null

Callbacks

Formatting

  • formatData (data) function, null

    Format the raw data that's returned from the ajax request. Useful for further filtering the data or returning the array of results that's embedded deeper in the object.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: array of objects to use as the data.


    • data array, object Data returned from the request.

  • formatError ($item, jqXHR, textStatus, errorThrown) function, null

    Format the text that's displayed when the ajax request fails. The message is displayed in a list item with the classmp_error:

    <li class="mp_error">
      <em>Your search could not be completed at this time.</em>
    </li>

    Setting this option to null or returning false suppresses the message from being displayed.

    Default:

    return '<em>Your search could not be completed at this time.</em>';

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: stringDOM element, or jQuery object to use as the message.


    • $item jQuery object List item to display the message.

    • jqXHR object or XMLHTTPRequest in jQuery 1.4.x.

    • textStatus string Error status of the request.

    • errorThrown string HTTP error status.

  • formatItem (data, $item) function

    Format the display of each item in the results list. By default, the title or name value of the data object is displayed. The returned value is added to a list item with the class mp_item:

    <li class="mp_item">The Title of Something</li>

    Default:

    return data.title || data.name;

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: stringDOM element, or jQuery object to use as the display.


    • data string, object Data returned from the request.

    • $item jQuery object List item to display the result.

  • formatMinChars (minChars, $item) function, null

    Format the text that's displayed when the minimum number of characters (specified with the minChars option) hasn't been reached. The message is displayed in a list item with the class mp_min_chars:

    <li class="mp_min_chars">
      <em>Your search must be at least <strong>3</strong> characters.</em>
    </li>

    Setting this option to null or returning false suppresses the message from being displayed. It is also not displayed when there is no input value.

    Default:

    return '<em>Your search must be at least <strong>' + minChars + '</strong>characters.</em>';

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: stringDOM element, or jQuery object to use as the message.


    • minChars integer Minimum number of characters required.

    • $item jQuery object List item to display the message.

  • formatNoResults (q, $item) function, null

    Format the text that's displayed when there are no results returned for the requested input value. The message is displayed in a list item with the class mp_no_results:

    <li class="mp_no_results">
      <em>No results for <strong>something</strong>.</em>
    </li>

    Setting this option to null or returning false suppresses the message from being displayed.

    Default:

    return '<em>No results for <strong>' + q + '</strong>.</em>';

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Return: stringDOM element, or jQuery object to use as the message.

    • string Requested input value.

    • $item jQuery object List item to display the message.

Events

  • onBlur () function, null

    Called when the user is finished interacting with the autocomplete interface, not just the text input, which loses and gains focus on a results list mouse click.

    Default: null

    Parameters: none

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopoloblur event:

    $(selector).on('marcopoloblur', function (event) { … });

  • onChange (q) function, null

    Called when the input value changes.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolochange event:

    $(selector).on('marcopolochange', function (event, q) { … });

    • string Changed input value.

  • onError ($item, jqXHR, textStatus, errorThrown) function, null

    Called when the ajax request fails.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopoloerror event:

    $(selector).on('marcopoloerror', function (event, $item, jqXHR, textStatus, errorThrown) { … });

    • $item jQuery object List item to display the message.

    • jqXHR object or XMLHTTPRequest in jQuery 1.4.x.

    • textStatus string Error status of the request.

    • errorThrown string HTTP error status.

  • onFocus () function, null

    Called when the text input receives focus. This is different than the standard focus event on the text input, however, as this callback does not fire when a results list item is selected via mouse click, which causes the text input to blur and immediately gain focus again.

    Default: null

    Parameters: none

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolofocus event:

    $(selector).on('marcopolofocus', function (event) { … });

  • onMinChars (minChars, $item) function, null

    Called when the minimum number of characters (specified with the minChars option) hasn't been reached by the end of the delay.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolominchars event:

    $(selector).on('marcopolominchars', function (event, minChars, $item) { … });

    • minChars integer Minimum number of characters required.

    • $item jQuery object List item to display the message.

  • onNoResults (q, $item) function, null

    Called when there are no results returned for the request.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolonoresults event:

    $(selector).on('marcopolonoresults', function (event, q, $item) { … });

    • string Requested input value.

    • $item jQuery object List item to display the message.

  • onRequestBefore () function, null

    Called before the ajax request is made. Useful for showing a loading spinner if the request is going to take some time.

    Default: null

    Parameters: none

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolorequestbefore event:

    $(selector).on('marcopolorequestbefore', function (event) { … });

  • onRequestAfter (jqXHR, textStatus) function, null

    Called after the ajax request completes (success or error). Useful for hiding a loading spinner that's shown inonRequestBefore.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopolorequestafter event:

    $(selector).on('marcopolorequestafter', function (event, jqXHR, textStatus) { … });

    • jqXHR object or XMLHTTPRequest in jQuery 1.4.x.

    • textStatus string Status of the request.

  • onResults (data) function, null

    Called when there are results to be displayed.

    Default: null

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopoloresults event:

    $(selector).on('marcopoloresults', function (event, data) { … });

    • data array Data returned from the request.

  • onSelect (data, $item, initial) function, null

    Called when an item is selected from the results list or an initial value (see Setting an Initial Value). By default, the title orname value of the data object is used to populate the input value.

    Default:

    this.val(data.title || data.name);

    Parameters:

    this: jQuery object Text input (no need to wrap like $(this)).

    Event: You can also bind to the marcopoloselect event:

    $(selector).on('marcopoloselect', function (event, data, $item, initial) { … });
    • data string, object Data returned from the request.

    • $item jQuery object, null Selected results list item. null if selected option used.

    • initial boolean Whether this is an initial value.

Methods

  • change

    Programmatically change the input value without triggering a search request (use the search method for that). If the value is different than the current input value, the onChange callback is fired.

    Example:

    $('#userSearch').marcoPolo('change', 'Wilson');

    Parameters:


    • string New input value.

  • destroy

    Remove the autocomplete functionality and return the selected input fields to their original state.

    Example:

    $('#userSearch').marcoPolo('destroy');

  • list

    Get the results list element.

    Example:

    $('#userSearch').marcoPolo('list');

  • option

    Get or set one or more options.

    Example:

    Get a specific option:

    $('#userSearch').marcoPolo('option', 'url');

    Get the entire options object:

    $('#userSearch').marcoPolo('option');

    Set a specific option:

    $('#userSearch').marcoPolo('option', 'url', '/new/url');

    Set multiple options:

    $('#userSearch').marcoPolo('option', {
      url: '/new/url',  onSelect: function (data, $item) { … }
    });

    Parameters:


    • nameOrValues string, object Optional options to get or set.

    • value mixed Optional option value to set.

  • search

    Programmatically trigger a search request using the existing input value or a new one. The input receives focus to allow for keyboard navigation.

    Example:

    Trigger a search on the existing input value:

    $('#userSearch').marcoPolo('search');

    Trigger a search on a new value:

    $('#userSearch').marcoPolo('search', 'Wilson');

    Parameters:


    • string Optional new input value to search on.

  • select

    Set the currently selected data, just as if the user clicked or keyboard selected an item from the results list. The onSelectcallback is fired.

    Example:

    $('#userSearch').marcoPolo('select', { first_name: 'Lindsay', … });

    Parameters:


    • data string, object Data of the selected item.

  • selected

    Get the currently selected data (stringobject, or null if not set).

    Example:

    $('#userSearch').marcoPolo('selected');

bootstrap风格的multiselect插件——类似邮箱收件人样式的更多相关文章

  1. jQuery分页插件jBootstrapPage,一个Bootstrap风格的分页插件

    一个Bootstrap风格的分页控件,对于喜欢Bootstrap简洁美观和扁平化的同学可以关注jBootstrapPage, 目前jBootstrapPage最新版为V0.1,后续还有更多功能需要完善 ...

  2. 自己写的基于bootstrap风格的弹框插件

    自己写的一款基于bootstrap风格的弹框插件,暂时只有确认框.提示框.后续功能扩展.bug修改再更新. ;(function($){ //默认参数 var PARAMS; var DEFAULTP ...

  3. Bootstrap风格zTree树形菜单插件

    这是一款bootstrap风格jQuery zTree树形菜单插件,支持自定义编辑.添加列表菜单.删除列表等功能的jQuery树形菜单代码.在线演示 具体代码实现: <!DOCTYPE html ...

  4. bootstrap 支持的JavaScript插件

    一次性导入: Bootstrap提供了一个单一的文件,这个文件包含了Bootstrap的所有JavaScript插件,即bootstrap.js(压缩版本:bootstrap.min.js). 具体使 ...

  5. 【ztree系列——图标的修改】Bootstrap风格的ztree

    前段时间项目中需要用树形结构,在选取的时候参考了很多插件,经过很多尝试,最后又回归到了ztree上.以前用的界面框架是EasyUI,但是它的树结构在实现起来有点复杂,并且功能不是特别完善.dtree在 ...

  6. Bootstrap WPF Style,Bootstrap风格的WPF样式

    简介 GitHub地址:https://github.com/ptddqr/bootstrap-wpf-style 此样式基于bootstrap-3.3.0,样式文件里的源码行数都是指的这个版本.CS ...

  7. 基于Metronic的Bootstrap开发框架经验总结(5)--Bootstrap文件上传插件File Input的使用

    Bootstrap文件上传插件File Input是一个不错的文件上传控件,但是搜索使用到的案例不多,使用的时候,也是一步一个脚印一样摸着石头过河,这个控件在界面呈现上,叫我之前使用过的Uploadi ...

  8. 基于jquery的bootstrap在线文本编辑器插件Summernote

    Summernote是一个基于jquery的bootstrap超级简单WYSIWYG在线编辑器.Summernote非常的轻量级,大小只有30KB,支持Safari,Chrome,Firefox.Op ...

  9. Bootstrap <基础三十一>插件概览

    在前面布局组件中所讨论到的组件仅仅是个开始.Bootstrap 自带 12 种 jQuery 插件,扩展了功能,可以给站点添加更多的互动.即使不是一名高级的 JavaScript 开发人员,也可以着手 ...

随机推荐

  1. android学习笔记46——File存储

    File存储--IO操作文件 openFileOutput.openFileInput Context提供了如下两个方法来打开本应用程序的数据文件夹里面的文件IO流. 1.FileInputStrea ...

  2. Metro 应用无法打开解决办法

    1.恢复默认UAC设置: 2.恢复自带防火墙服务启动类型为自动: 3.设置IE为默认浏览器(搜索和应用中): 4.如有可能使用Microsoft帐户,而不是本地帐户(仅使用有限的几个Metro应用): ...

  3. 一个 IT 青年北漂四年的感悟

    转载自:http://www.codeceo.com/article/it-man-beijing-4-years.html 工作这几年,每年都会有朋友离开北京,每次朋友跟我告别的时候总是让我有很多感 ...

  4. UDP程序设计

        UDP是不可靠的连接,广泛应用于各种聊天工具     使用UDP发送的信息,对方不一定会接收到.所有的信息使用数据报的形式发送出去,这就要求客户端要始终等待服务器发送的信息才能进行接收.在Ja ...

  5. 补一篇关于Jackson和Gson的文章

    一.关于Gson的问题 问题1. 如果对象属性里有[],表示它是一个列表,需要用List对象进行封装,不能用String来定义,不然转不了 问题2. Gson在解析的时候,如果json中有转义字符 \ ...

  6. [Bug-IOS] - linker command failed with exit code 1 (use -v to see invocation)

    Ld /Users/Rubert/Library/Developer/Xcode/DerivedData/OC_Language-emftyzftyvhdpuaxipddjmpnpvox/Build/ ...

  7. JAVA 99乘法表实例

    实例: public class Test{ public static void main(String[] args){ for(int i=1;i<=9;i++){ for(int j=1 ...

  8. 庭审全程文字实录 z

    备受关注的深圳快播公司涉黄案两日来在北京市海淀法院开庭审理,快播CEO王欣(微博).事业部总经理吴铭.事业部副总经理张克东.事业部副总经理兼市场部总监牛文举出庭接受审理. 面对传播淫秽物品牟利罪的指控 ...

  9. 更新nvm

    在官方看到这个文档 ( cd "$NVM_DIR" git fetch origin git checkout `git describe --abbrev=0 --tags -- ...

  10. ruby关于flip-flop理解上一个注意点

    (..).each do |x| puts x ) .. (x == ) end 上面的flip-flop的用法,你可以理解成 将 大于等于5和小于等于10的数字打印出来,也就是理解成  puts x ...