【问题标题】:Keep Select2 open (Never collapse/allow size attribute)保持 Select2 打开(从不折叠/允许大小属性)
【发布时间】:2016-12-02 13:18:55
【问题描述】:

注意:我的示例在JSFiddle

我有一个这样的列表框:

<select id="plain" size="3">
  <option value="first">First</option>
  <option value="second">Second</option>
  <option value="third">Third</option>
  <option value="fourth">Fourth</option>
</select>

请注意,列表框会立即在屏幕上显示 3 个项目:

我想让这个列表框更容易搜索,所以我使用了 Select2:

HTML:

<select id="fancy" size="3">
  <option value="first">First</option>
  <option value="second">Second</option>
  <option value="third">Third</option>
  <option value="fourth">Fourth</option>
</select>

JS:

$('#fancy').select2();

但结果是:

我希望size="3" 能够获得荣誉,但我不知道怎么做。有closeOnSelect: false(来自this question),但双击后它仍然关闭。我的 Google 搜索是 not 非常 fruitful

【问题讨论】:

    标签: javascript html jquery-select2


    【解决方案1】:

    这似乎不是 select2 库的一部分,但您可以为此使用一些 javascript:

    var list = $("#fancy").select2({
      closeOnSelect: false
    }).on("select2:closing", function(e) {
      e.preventDefault();
    }).on("select2:closed", function(e) {
      list.select2("open");
    });
    list.select2("open");
    

    现在的问题是 select2 并没有真正只显示您想要的 3 个项目(而是全部 4 个)。要解决这个问题,您可以更改 css(但您必须说出打开菜单的确切高度):

    .select2-container--default .select2-results > .select2-results__options {
        max-height: 90px
    }
    

    90px 是您的示例。在不同的 font-size/font-family/etc 中可能会有所不同。

    并隐藏选择箭头:

    .select2-selection__arrow {
        display: none
    }
    

    这里是您的 jsfiddle 的更新:
    https://jsfiddle.net/pk9fu6mn/2/

    【讨论】:

    • 这正是我所需要的,谢谢。我可以加.select2-selection__arrow { display: none }吗?这将隐藏不再具有功能的向下箭头。
    • 是的,我猜你会想要那个 :) 欢迎你更新我的答案,如果你愿意,可以添加它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多