简体   繁体   English

如何更改每个select2选项的背景?

[英]How to change the background of each select2 option?

I'm using select2 for a dropdown selection box and I'm trying to change the background color of the options.我正在使用 select2 作为下拉选择框,并且我正在尝试更改选项的背景颜色。 There would be a separate color for each option.每个选项都有单独的颜色。 I've tried by adding a style attribute to the options but it doesn't seem to work.我已尝试向选项添加样式属性,但似乎不起作用。

<select class="js-example-basic-multiple form-control" id="select-tags" name="usertags" multiple="multiple">
        {% for tag in userTags %}
        <option value="{{ tag }}" data-id="{{ tag.color }}" style="background-color:{{ tag.color }}" class="options">{{ tag }}</option>
        {% endfor %}
    </select>

$('.js-example-basic-multiple').select2();

Adding background colors to the <option> elements inside your <select> isn't working because those elements end up hidden.<select>内的<option>元素添加背景颜色不起作用,因为这些元素最终被隐藏了。 Select2 hides the original <select> , then generates its own elements to produce a styled "fake" select control which mirrors the value of the hidden "real" one. Select2 隐藏原始<select> ,然后生成它自己的元素以生成一个样式化的“假”选择控件,它反映了隐藏的“真实”选择控件的值。

注意 select 元素上的“aria-hidden”属性

Since select2 doesn't provide an API for passing color values to individual options, you'll need to try either using nth-child() selectors in CSS or some extra javascript to style the fake option elements that select2 creates.由于 select2 不提供用于将颜色值传递给单个选项的 API,您需要尝试在 CSS 中使用nth-child()选择器或一些额外的 javascript 来设置 select2 创建的假选项元素的样式。 Here's a question from 2018 with answers demonstrating each approach. 这是 2018 年的一个问题,其中的答案展示了每种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM