我有一个 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 会做以下事情:
添加了一些
<span>
进入你的<select>
; (可以console.log($('select').html())
查看添加了什么)创建一个
<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/