如何使用CSS更改select2控件的字体颜色

7
我正在使用以下HTML代码将select2控件包含在我的表单中,如下所示。
<select id="element_id" class="select2" style="width:100%">
<option value="e1" >Element 1</option>
<option value="e2" >Element 2</option>
<option value="e3" >Element 3</option>
</select>

我正在使用以下样式来格式化列表项目和选定项目的字体。
<style>
    #s2id_element_id .select2-container--default .select2-selection--single .select2-selection__rendered 
    {
        color: green ;
    }
</style>

这不会将列表项和选定项目涂成绿色。 注意:我只需要这个特定的下拉框有样式,而不是其他下拉框。因此,我使用CSS ID选择器来针对特定的select2控件。
谢谢。

1
这不是排版错误,我也尝试了element_id和s2id_element_id。 - Wajira Weerasinghe
5个回答

26

以下是你需要使用的类来为 select2 输入框进行样式设置:

/* Input field */
.select2-selection__rendered {  }
    
/* Around the search field */
.select2-search {  }
    
/* Search field */
.select2-search input {  }
    
/* Each result */
.select2-results {  }
    
/* Higlighted (hover) result */
.select2-results__option--highlighted {  }
    
/* Selected option */
.select2-results__option[aria-selected=true] {  }
如果您愿意,可以在我创建的JSBin中玩耍,以便您可以测试一些东西。

我已更新我的JSBin,在其中您可以看到如何为特定的select2列表设置样式(而不是全局添加样式)


我希望这是您在寻找的答案(或许更多)。如果不是,我很乐意提供额外的信息。 - Mihailo
嗨Mihailo,谢谢你的努力。我想要的是在选择器中使用element_id来包含一个额外的选择器。我只需要给特定的select2控件上色,而不是表单中所有的select2控件。只有这个特定的控件需要上色。所以我尝试将id选择器放在列表的第一位,但是没有起作用。我尝试过#s2id_element_id和#element_id,但都没有起作用。 - Wajira Weerasinghe
例如,我期望以下代码能够准确地过滤我的特定select 2控件:#element_id .select2-selection__rendered {background-color:yellow; } - Wajira Weerasinghe
啊,抱歉之前没有正确理解你的问题。我已经更新了_JSBin_,提供了使用给定ID样式化特定select2的代码。希望你会觉得有用。 - Mihailo
@WajiraWeerasinghe 哈哈哈,你是个传奇,我两周前穿了这件衣服 xD 很高兴能帮到你。:] - Mihailo
非常感谢。@Mihailo,你救了我。 - Ruberandinda Patience

2
.select2-results .select2-highlighted {
    background: #3ea211;
}

试试这个 CSS,它会很好地工作


0
.select2-container--default .select2-results__option--highlighted[aria-selected] {
   background-color: #5897fb !important;
   color: white;
}

试一下这个


0
$("#select2-**element_id**-container").css('color','green');

0
<select id="listcolors" name="color[]" class="js-example-placeholder-multiple js-states form-control"
                multiple="multiple">

    @foreach ($colors as $item)
        <option value="{{ $item->id }}" title="{{ $item->color_code }}">{{ $item->color_name }}
        </option>
    @endforeach

</select>

<script>
                
    function formatState(state) {
        if (!state.id) {
            return state.text;
        }
        var $state = $(
            '<span><img width="10" height="10" style="background-color:' + state.element.title + ';"  /> ' + state
                        .text + '</span>'

        );
        return $state;
    };

    $("#listcolors").select2({
        templateResult: formatState,
        placeholder: "Choisir une couleur"
    });
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接