如何使用 HTML 5 和 CSS 3 显示彩色下拉选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6311722/
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
How do I display a coloured drop down selector with HTML 5 and CSS 3?
提问by Thierry Lam
I have a basic html select:
我有一个基本的 html 选择:
<select>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Grape</option>
</option>
I want to set the background colour of each option to a different one. For instance, Apple is red, Banana is yellow and Grape is purple. By initiating a drop down, I will see the different colours in each option.
我想将每个选项的背景颜色设置为不同的颜色。例如,苹果是红色的,香蕉是黄色的,葡萄是紫色的。通过启动下拉菜单,我会在每个选项中看到不同的颜色。
Is it possible to achieve the above with CSS3/HTML5 on the latest Firefoxand Webkit(Chrome and Safari) browsers?
是否可以在最新的Firefox和Webkit(Chrome 和 Safari)浏览器上使用 CSS3/HTML5 实现上述目标?
NOTE: Can you test your solutions on both the latest Firefox and Chrome, possibly on the Mac? I'm aware of the background colour method but it only works in Firefox on the Mac.
注意:您能否在最新的 Firefox 和 Chrome(可能在 Mac)上测试您的解决方案?我知道背景颜色方法,但它只适用于 Mac 上的 Firefox。
回答by thirtydot
Is it not just as easy as this? http://jsfiddle.net/d8p8Q/
难道就这么简单吗?http://jsfiddle.net/d8p8Q/
<select>
<option value="1" style="background:red">Apple</option>
<option value="2" style="background:yellow">Banana</option>
<option value="3" style="background:purple">Grape</option>
</select>
Am I missing something here?
我在这里错过了什么吗?
Safari
Chrome (and I'm using Windows 7)
Safari
Chrome (我使用的是 Windows 7)
"Grape" is blue because that's the one I'm hovering over. I don't think it's possible to change that blue "selected" colour using the native <select>
element.
“葡萄”是蓝色的,因为那是我悬停在上面的那个。我认为不可能使用本机<select>
元素更改蓝色的“选定”颜色。
If that's what you're after doing, you'll have to swap out the <select>
s with JavaScript replacements, such as these:
如果这就是你所做的,你将不得不<select>
用 JavaScript 替换来替换 s,例如:
回答by scurker
/* Style */
select option[value="1"] {
background-color: #f00;
}
select option[value="2"] {
background-color: #0f0;
}
select option[value="3"] {
background-color: #00f;
}
<!-- HTML -->
<select>
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
Of course it would be easier to target with classes, but this should get you started.
当然,以类为目标会更容易,但这应该可以帮助您入门。
回答by ngen
Like this? http://jsfiddle.net/3HWUw/1/
像这样?http://jsfiddle.net/3HWUw/1/
HTML:
HTML:
<select>
<option id="one" value="1">Apple</option>
<option id="two" value="2">Banana</option>
<option id="three"value="3">Grape</option>
</select>
CSS:
CSS:
#one {
background-color: red;
}
#two {
background-color: yellow;
}
#three {
background-color: green;
}
回答by Bantros
The above works, or you can do it in CSS like this:
上面的工作,或者你可以在 CSS 中这样做: