简体   繁体   English

仅更改所选选项的颜色

[英]Change color of selected option only

I have a selector sitting in a table cell. 我有一个选择器坐在一个表格单元格中。 The table row has a color, so using CSS I can change the drop-down's background to the same color by using background-color:inherit; 表行有颜色,所以使用CSS我可以使用background-color:inherit;将下拉的背景更改为相同background-color:inherit; However, it changes the color of the entire box with all options. 但是,它会使用所有选项更改整个框的颜色。

Is it possible to change the color of the selected option only, if not with CSS perhaps with a help of jQuery? 是否可以仅更改所选选项的颜色,如果没有CSS可能借助jQuery?

Everything is possible with jQuery :) You should try this: 使用jQuery可以实现一切:)你应该试试这个:

$('.mySelect').change(function () {
    $(this).find('option').css('background-color', 'transparent');
    $(this).find('option:selected').css('background-color', 'red');
}).trigger('change');

And here is a live demo 这是一个现场演示

Hope that helps! 希望有所帮助!

I was able to do it by first setting the background color of the SELECT element to what I wanted resulting in all options being that color. 我能够通过首先将SELECT元素的背景颜色设置为我想要的结果来实现,从而导致所有选项都是该颜色。 Then I made all the options a specific color scheme. 然后我将所有选项都设为特定的配色方案。 Finally I made the selected option the same color scheme as the SELECT element so the option shows the same color in the drop down list. 最后,我使所选选项与SELECT元素具有相同的颜色方案,因此该选项在下拉列表中显示相同的颜色。

$.each($('select'), function(i,v) {

    theElement = $(v);
    theID = theElement.attr('id');

    // Set the SELECT input element to green background with white text

    theElement.css('background-color', 'green');
    theElement.css('color', 'white');

    // Set all the options to another color (note transparant will show the green)

    $('#'+theID).find('option').css('background-color', 'white');
    $('#'+theID).find('option').css('color', 'black');

    // Finally set the selected option to the same values as the SELECT element

    $('#'+theID).find('option:selected').css('background-color', 'green');
    $('#'+theID).find('option:selected').css('color', 'white');
});

You should be able to do this with jQuery. 你应该能够用jQuery做到这一点。 I may be wrong (see David Thomas' comment), but try: 我可能错了(参见David Thomas的评论),但尝试:

$("option[value='myValue']").css('background-color', 'red');

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

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