繁体   English   中英

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

[英]Changing The Font Colour for a Select2 Option at the Change Event

我有一个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> <select> (您可以console.log($('select').html())查看添加的内容)

  2. 在正文下方创建一个<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> 

暂无
暂无

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

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