在更改事件中更改 select2 选项的字体颜色



我有一个 Select2 选项元素,可以检测并警告用户是否通过更改背景颜色(使用以下代码(更改了默认设置(

$(document).on('change', ".ctaskSelector", function(e) {
 var val =  $(this).val();
 var index = $(".ctaskSelector").index(this);
 if ( val != taskData[index].task_ID)
    $(this).next().find('.select2-selection').css({'background-color':'red'})
 else
    $(this).next().find('.select2-selection').css({'background-color':'white'})

更改背景颜色被证明过于强烈,因为它掩盖了文本字段。 与其更改背景颜色,我只想更改显示项目的字体颜色。 我已经尝试了几乎所有的css选项(如何使用css更改select2控件的字体颜色 但似乎找不到只会更改所选选项字体颜色的那个。

谁能帮忙。

如果要

更改该select2内所选选项的字体颜色,请尝试以下代码:

原因是 select2 将执行以下操作:

  1. 在您的<select>中添加了一些<span>;(您可以console.log($('select').html())查看添加的内容(

  2. 在 body 下创建一个<span class="selection">,然后使用 position=absolute 将其放置在<select>上方

所以你需要先获取id(通过$('span[aria-owns]', this).attr('aria-owns')(,然后通过 $('#'+ id) 找到该元素,最后更改背景或其他您喜欢的内容。

$('select').select2();
//change the background-color for select
$('.select2 span').css('background-color', 'yellow')
$('.select2').click(function(){
  //you can uncomment below codes to see its structure
  //console.log($('.select2-container').html())
  //below change the background color for the input
  $('#'+$('span[aria-owns]', this).attr('aria-owns'))
    .parent()
    .siblings('.select2-search')
    .find('input')
    .css('background-color', 'green')
  //below change the font color for the selected option
  $('#'+$('span[aria-owns]', this).attr('aria-owns'))
    .find('li[aria-selected=true]')
    .css('color', 'red')
  //below change the font color for <select>
  $('>span>span>span', this).css('color', 'blue')
  //below change the background color for the arrow of <select>
  $('>span .select2-selection__arrow', this).css('background-color', 'red')
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select class="select2" style="width:100%">
  <option value="e1" >Element 1</option>
  <option value="e2" >Element 2</option>
  <option value="e3" >Element 3</option>
</select>

最新更新