只改变所选选项的颜色

9

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

如果不能使用CSS仅更改所选选项的颜色,那么是否可以借助jQuery实现?


2
你能展示一下你的HTML和CSS吗?顺便说一句,样式化选择框非常困难! - Jason Gennaro
2
可能不行,浏览器似乎对 select 元素的样式具有有限的访问权限。 - David Thomas
3个回答

10

使用jQuery,一切皆有可能 :) 你应该尝试这个:

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

这里还有一个实时演示

希望对你有所帮助!


Ronn的答案考虑了选定项目在不活动和点击并展开时的情况。 - Ohiovr

4

我能够通过将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');
});

1
答案自2011年10月12日起就在那里!此外,它已被接受。 - Ozzy

3
您可以使用jQuery来实现此操作。我可能错了(请参见David Thomas的评论),但是尝试一下以下代码:
$("option[value='myValue']").css('background-color', 'red');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接