首页 > 解决方案 > Select2 Bootstrap 主题 如何修复不正确的样式显示?

问题描述

我将 Select2 与 Bootstrap 主题(https://github.com/ttskch/select2-bootstrap4-theme)一起使用。这是我的选择:

<select style="width: 100%;" id="languages_select" class="form-control js-example-basic-multiple" multiple="multiple" onchange="get_languages()">
    {% for id, name in languages.items %}
        <option value="{{ id }}">{{ name }}</option>
    {% endfor %}
</select>

而且我在显示此字段时遇到了一些错误。看起来这个问题与兼容性有关,但我使用的是受支持的Bootstrap 4.1 。示例: 在此处输入图像描述 这个白色边框间隙似乎是由占位符文本跨度引起的,我无法在我的 html 中更改它,因为它是由 Select2 在一切之后呈现的。 在此处输入图像描述 这个很奇怪。这个删除按钮看起来没有样式。

我知道 jQuery、CSS 或 JS 的链接顺序可能会导致问题,所以这是我的导入顺序:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

UPD:更改顺序后选择 在此处输入图像描述

标签: htmlcssbootstrap-4jquery-select2

解决方案


就像你说的导入css的顺序很重要。因此您需要将您的 css 链接顺序重新排序为:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">    
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

确保在使用 select2 初始化选择时也将主题设置为 bootstrap4。像这样:

    $('select').select2({
        theme: 'bootstrap4',
    });

这在https://github.com/ttskch/select2-bootstrap4-theme的自述文件中有所提及

这是一个工作示例:

$('select').select2({
        theme: 'bootstrap4',
    });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<select class="form-control">
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
</select>


推荐阅读