用户使用 select2 更改所选项目的字体颜色

Changing font color of selected item by user with select2

我有简单的 select 选项 html:

<select name="individual_taxCountry" id="individual_taxCountry" class="select2">
<option value="" selected="selected" class="selected">Select a country</option>
<option value="Afghanistan" >Afghanistan</option>
<option value="Aland Islands" >Aland Islands</option>
<option value="Albania" >Albania</option>
<option value="Algeria" >Algeria</option>
<option value="Zambia" >Zambia</option>
<option value="Zimbabwe" >Zimbabwe</option>
</select>

我为此使用 select2:

$(document).ready(function(){
$(".select2").select2();
});

而且我还自定义了 select 的显示方式 css:

.select2-container--default .select2-selection--single
{
    background-color: #21262d;
    border-color: #21262d;
    border-top-color: #21262d;
    border-right-color-value: #21262d;
    border-bottom-color: #21262d;
    border-left-color-value: #21262d;
    height: 34px;
}

它看起来是我想要的方式,但我想在用户这样做时将 selected 项目的字体颜色更改为白色。我怎样才能做到这一点?

http://jsfiddle.net/bhuffprL/

编辑:因为不是每个人似乎都理解我的目标 - 我只想在用户 selects his/her 拥有列表中的项目时更改为白色 (fff) .我想要的默认选项是深色。 换句话说:'Select a country' 应该是深色,当用户 select 是列表中的一个国家时,我想更改字体颜色变白。

只需将此 css 添加到您的 css 代码

.select2-container--default .select2-selection--single .select2-selection__rendered{
    color: #fff
}


https://jsfiddle.net/bhuffprL/

我可以想到一些使用 JS 的解决方案,但不确定使用 select2 插件是否有更简单的方法。

我能想到的更简单的方法是创建一个占位符而不是默认选项。

发件人:

$(document).ready(function(){
  $(".select2").select2();
});

收件人:

$(document).ready(function(){
  $("#individual_taxCountry").select2({
    placeholder: "Select a state*"
  });
});

然后在您的 html 上设置一个空的选项值,其中将出现占位符。

替换为:

<option value="" selected="selected" class="selected">Select a country*</option>

为此:

<option></option> 

然后为字体颜色添加必要的css

.select2-container--default .select2-selection--single .select2-selection__placeholder {
  color: #444;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    color: #fff;
}

Fiddle