javascript - 在更改事件中更改 Select2 选项的字体颜色

标签 javascript jquery css jquery-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 选项(How to change font color of select2 control using css ,但似乎无法找到只会更改所选选项字体颜色的选项。

谁能帮忙。

最佳答案

如果您想更改 select2 中所选选项的字体颜色,试试下面的代码:

原因是 select2 会做以下事情:

  1. 添加了一些 <span>进入你的<select> ; (可以console.log($('select').html())查看添加了什么)

  2. 创建一个 <span class="selection">在 body 下面然后使用 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>

关于javascript - 在更改事件中更改 Select2 选项的字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910493/

相关文章:

javascript - Opera,自定义上下文菜单,右键单击

javascript - 获得 childnodes child 直到没有

javascript - ruby on Rails jquery 未调用正确的 Controller 操作

javascript - jquery 根据索引将脚本应用于所有 div

javascript - jQuery 变形类

css - 如何使 CSS "inch"单位等于物理英寸?

html - 响应式表格使用 CSS 显示 : table-row

mysql - 在 mysql 数据库的 core_config_data 中编辑 web/unsecure/base_url 后,Magento 站点 css 未加载

javascript - 如何制作一个干净的模板并将多个项目传递给它?

javascript - Dynamics 2016 本地 Crm 客户端脚本。缺少选项集控件类型的方法