简体   繁体   English

如何在选择标签中设置所选选项的颜色

[英]How to set the color of a selected option in a select tag

I'm trying to set the color of the selected option in a select tag that has a size of 5 so it acts as a list box. 我正在尝试在大小为5的选择标记中设置选定选项的颜色,以使其充当列表框。

I can get it working when the select tag acts as a drop down but when I make it a list box the selected option is always grey when I unfocused it. 当select标签用作下拉菜单时,我可以使它工作,但是当我将其设为列表框时,当我将其置于非焦点状态时,所选选项始终为灰色。

Here's a code example of what is happening. 这是正在发生的事情的代码示例。 The first select tag is acting correctly, but as soon as I apply the size attribute, the color of the selected option will be grey. 第一个select标签运行正常,但是一旦我应用了size属性,所选选项的颜色就会变成灰色。

 select { margin: 40px; background: yellow; color: #000; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4); } option:not(:checked) { background-color: #FFF; } 
 <select> <option val="">Select Option</option> <option val="1">Option 1</option> <option val="2" selected>Option 2</option> <option val="3">Option 3</option> <option val="4">Option 4</option> </select> <br/> <select size="5" multiselect> <option val="">Select Option</option> <option val="1">Option 1</option> <option val="2" selected>Option 2</option> <option val="3">Option 3</option> <option val="4">Option 4</option> </select> 

After checking on JS Fiddle on different browsers, it appears to be a browser style that is getting set. 在不同的浏览器上检查JS Fiddle之后,它似乎是一种已设置的浏览器样式。

Below are images from Chrome, Firefox and Internet Explorer. 以下是来自Chrome,Firefox和Internet Explorer的图像。 Both chrome and firefox seem to set their own value, internet explorer will not though. chrome和firefox似乎都设置了自己的价值,但Internet Explorer不会。

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

To do that, you have to set the background property of the option in CSS. 为此,您必须在CSS中设置optionbackground属性。

 select, select option:active, select option:checked{ margin:40px; background: yellow; color:#000; text-shadow:0 1px 0 rgba(0,0,0,0.4); } option:not(:checked) { background-color: #FFF; } 
 <select> <option val="">Select Option</option> <option val="1">Option 1</option> <option val="2" selected>Option 2</option> <option val="3">Option 3</option> <option val="4">Option 4</option> </select> <br/> <select size="5" multiselect> <option val="">Select Option</option> <option val="1">Option 1</option> <option val="2" selected>Option 2</option> <option val="3">Option 3</option> <option onfocus="this.style.background='red'" val="4">Option 4</option> </select> 

You can try adding a background gradient in case of multi select like below. 您可以尝试添加背景渐变,以防多重选择,如下所示。 You need to add properties to make this work in cross browser though. 但是,您需要添加属性以使其在跨浏览器中起作用。

select[multiselect] option:checked {
    background: -moz-linear-gradient(left, yellow 0%, yellow 100%);
 }

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

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