2011-10-12 156 views
5

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

是否有可能只改变所选择的选项的颜色,如果没有CSS可能与jQuery的帮助?

+2

你能告诉我们你的html和css吗? Fyi ...造型选择框非常困难! –

+2

可能不是,不;浏览器似乎只能访问'select'元素的样式。 –

回答

4

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

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

这里是一个live demo

希望有帮助!

+0

实时演示不适用于Chrome/OSX –

+0

Ronn的回答考虑了选中的项目在非活动状态以及点击和展开时的情况。 – Ohiovr

0

你应该可以用jQuery来做到这一点。我可能是错的(见大卫托马斯的评论),但尝试:

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

我能够做到这一点,首先将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