Style select2多选框与单选框相同?

5
基本上我想要做的是,当点击字段时,使输入仅充当显示,我希望下拉菜单中的搜索字段与单选相同。下面是一个(糟糕的)示例图解释了这一点。

enter image description here

选择2是否内置了此功能,或者有没有简单的方法来实现它?

很难确定你究竟在寻找什么。看看插件Chosen,它是否符合你的要求? - Evan
Select2基于Chosen开发,可以查看演示页面来了解单选的工作原理。现在看看多选,我喜欢多选中的“标签”功能,但我不想在“标签输入”中输入,我希望像单选版本中那样出现一个搜索字段。 - Hailwood
这里有一个带有Select2的fiddle,如果有人想要尝试一下。http://jsfiddle.net/isherwood/yJYpY/ 我认为你需要修改S2核心才能让它正常工作。 - isherwood
1个回答

2

对于那些仍在寻找解决方案的人,请看我的fiddle。

我使用了一些关于这个问题发布的fiddle,并将它们合并为一个。

不是完美的,但它可以工作。

https://jsfiddle.net/Lkkm2L48/7/

jQuery(function($) {
    $.fn.select2.amd.require([
    'select2/selection/single',
    'select2/selection/placeholder',
    'select2/selection/allowClear',
    'select2/dropdown',
    'select2/dropdown/search',
    'select2/dropdown/attachBody',
    'select2/utils'
  ], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {

        var SelectionAdapter = Utils.Decorate(
      SingleSelection,
      Placeholder
    );

    SelectionAdapter = Utils.Decorate(
      SelectionAdapter,
      AllowClear
    );

    var DropdownAdapter = Utils.Decorate(
      Utils.Decorate(
        Dropdown,
        DropdownSearch
      ),
      AttachBody
    );

        var base_element = $('.select2-multiple2')
    $(base_element).select2({
        placeholder: 'Select multiple items',
      selectionAdapter: SelectionAdapter,
      dropdownAdapter: DropdownAdapter,
      allowClear: true,
      templateResult: function (data) {

        if (!data.id) { return data.text; }

        var $res = $('<div></div>');

        $res.text(data.text);
        $res.addClass('wrap');

        return $res;
      },
      templateSelection: function (data) {
        if (!data.id) { return data.text; }
        var selected = ($(base_element).val() || []).length;
        var total = $('option', $(base_element)).length;
        return "Selected " + selected + " of " + total;
      }
    })

  });

});

CSS:
.select2-results__option .wrap:before{
    font-family:fontAwesome;
    color:#999;
    content:"\f096";
    width:25px;
    height:25px;
    padding-right: 10px;

}
.select2-results__option[aria-selected=true] .wrap:before{
    content:"\f14a";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接