如何为每个select2选项使用不同的颜色?

时间:2018-04-12 16:25:39

标签: html css twitter-bootstrap-3 jquery-select2

我正在使用select2下拉菜单,并希望在每个选项上设置不同的颜色。

示例:

<select class="select2" name="fruit">
  <option class="red-option">Apple</option>
  <option class="green-option">Kiwi</option>
  <option class="blue-option">Grape</option>
</select>

我可以对渲染的,选定的选项进行着色,如下所示:

.select2-selection__rendered[title="Apple"] {
  color: red !important;
}

如何在select2下拉列表中对选项进行着色 - 基于选项类('red-option')或值('Apple')?

PS:我使用bootstrap 3.3 + jQuery,如果必须的话,不介意用JS来做这件事。

3 个答案:

答案 0 :(得分:1)

知道了。

Select2使用父select的{​​{1}}属性为所有下拉选项生成ID属性。

通过我的例子,我可以使用:nth-​​child(x)应用颜色如下:

name

答案 1 :(得分:0)

您可以在select2-results__option元素上使用CSS属性选择器:

$(".select2").select2();
.select2-selection__rendered[title="Apple"] {
  color: red !important;
}

.select2-results__option[id*="Apple"] {
  color: red;
}

select {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select class="select2" name="fruit">
  <option class="red-option">Apple</option>
  <option class="green-option">Kiwi</option>
  <option class="blue-option">Grape</option>
</select>

答案 2 :(得分:0)

我发现了使用选项的更好解决方案

function formatState(state) {
  const option = $(state.element);
  const color = option.data("color");

  if (!color) {
    return state.text;
  }

  return $(`<span style="color: ${color}">${state.text}</span>`);
};

jQuery(node).select2({
  templateResult: formatState,
  templateSelection: formatState,
});

在我的情况下,颜色来自html数据属性

<option style="color: #F00" data-color="#F00" value="1">Red Option</option>