jQuery 仅更改所选选项的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7741722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:13:51  来源:igfitidea点击:

Change color of selected option only

jquerycss

提问by santa

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;However, it changes the color of the entire box with all options.

我有一个位于表格单元格中的选择器。表格行有一种颜色,因此使用 CSS 我可以通过使用将下拉列表的背景更改为相同的颜色,background-color:inherit;但是,它会更改带有所有选项的整个框的颜色。

Is it possible to change the color of the selected option only, if not with CSS perhaps with a help of jQuery?

是否可以仅更改所选选项的颜色,如果不能在 jQuery 的帮助下使用 CSS?

采纳答案by Kristoffer Lundberg

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!

希望有帮助!

回答by Ronn

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. 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 元素的背景颜色设置为我想要的颜色来完成它,从而导致所有选项都是该颜色。然后我将所有选项设为特定的配色方案。最后,我使选定的选项与 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');
});

回答by jtfairbank

You should be able to do this with jQuery. I may be wrong (see David Thomas' comment), but try:

你应该可以用 jQuery 做到这一点。我可能是错的(见 David Thomas 的评论),但请尝试:

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