select2 with bootstrap theme - inside collapse

select2 with bootstrap theme - inside collapse

初始化隐藏时,我无法让 select2 下拉列表适合 parent 容器(折叠)。我知道这不是错误,因为 select2 无法计算 parent 宽度。但我无法克服这一点。我需要它达到 parent.

的 100%
<div class="panel panel-default">
  <div class="panel-body">
    <div class="btn-toolbar">
      <button class="btn btn-default" data-toggle="collapse" data-target="#collapse-select2" aria-expanded="false">Toggle</button>
    </div>
    <div class="collapse" id="collapse-select2">
      <select class="form-control" data-role="select2">
        <option value="1">Option #1</option>
        <option value="2">Option #2</option>
        <option value="3">Option #3</option>
      </select>
    </div>
  </div>
</div>

Fiddle: here

有人可以帮忙吗?

其实很简单的解决方法:

1。 CSS唯一的解决方案
.select2 100% 宽度并用 !important 覆盖,如下所示:

.select2 {
  width: 100%!important; /* overrides computed width, 100px in your demo */
}

这也是你的更新 fiddle https://jsfiddle.net/1agwbfmy/6/


2。 select
的样式标签 另一种方法,如 documentation 中所写,是用 style<select> 元素赋予宽度,它将从那里获取属性:
<select class="form-control" data-role="select2" style="width:100%">


3。插件配置
最后,你可以在jQuery中调用插件时设置宽度(如old docs中所写):

$('select[data-role="select2"]').select2({
    theme: 'bootstrap',
    width: '100%'
});

在配置中使用width: '100%'属性

$('[data-role="select2"]').select2({
   width: '100%',
   ...
});