如何为每个select2选项使用不同的颜色? [英] How to use different colors for each select2 option?

查看:152
本文介绍了如何为每个select2选项使用不同的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用select2下拉列表,并且希望在每个选项上设置不同的颜色.

I'm using a select2 dropdown, and would like to set different colours on each options.

示例:

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

我可以为呈现的选定选项着色,如下所示:

I can colourize the rendered, selected option as follow:

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

如何还根据选项类(红色选项")或值(苹果")为select2下拉菜单中的选项上色?

How to also colourize the options in the select2 dropdown - either based on the option class ('red-option') or value ('Apple')?

PS:我使用bootstrap 3.3 + jQuery,如果需要的话,我不介意使用JS来做到这一点.

PS: I use bootstrap 3.3 + jQuery and don't mind using JS to do this if I must.

推荐答案

知道了.

Select2使用父级selectname属性为所有下拉选项生成一个id属性.

Select2 generates an id attribute for all the dropdown options, using the parent select's name attribute.

在我的示例中,我可以使用:nth-​​child(x)来应用颜色,如下所示:

With my example, I was able to apply a colour using :nth-child(x) as follow:

.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(1) {
  color: red;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(2) {
  color: green;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(3) {
  color: blue;
}

<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选项使用不同的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆