我有一个select
元素,并使用第一个option
作为选择字段的标题.我想知道当select
选择第一个选项时是否有办法使字段内的文本变灰.这只能在JS中完成,还是有CSS解决方案?
我尝试更改第一个的样式,option
但只有在激活下拉菜单时才会更改文本的颜色.
<select>
<option>Please select your favourite fruit</option>
<option>Apple</option>
<option>Banana</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Tes*_*ssa 49
这是一个更现代的解决方案,因此它并不特定于第一个选项,而是一个无效的选项,并且不需要JS只显示标题/占位符选项为灰色,而其余选项显示正常.
select,
select option {
color: #000000;
}
select:invalid,
select option[value=""] {
color: #999999;
}
label {
display: block;
margin: 16px 0;
}
/*Added for browser compatibility*/
[hidden] {
display: none;
}
Run Code Online (Sandbox Code Playgroud)
<label>
Invalid option cannot be selected and is hidden from the user in the dropdown.
<select required>
<option value="" selected disabled hidden>Please select your favourite fruit</option>
<option>Apple</option>
<option>Banana</option>
</select>
</label>
<label>
Invalid option cannot be selected, but is not hidden from the user in the dropdown.
<select required>
<option value="" selected disabled>Please select your favourite fruit</option>
<option>Apple</option>
<option>Banana</option>
</select>
</label>
<label>
Invalid option can be selected and is not hidden from the user in the dropdown.
<select required>
<option value="" selected>Please select your favourite fruit</option>
<option>Apple</option>
<option>Banana</option>
</select>
</label>
Run Code Online (Sandbox Code Playgroud)
如果选择框是必需的,则select上的无效选择器仅对选项有效,并且所选选项的值为空,因此您可以像设置文本框的占位符文本一样对其进行样式设置.
将其设置为禁用可防止用户在选择选项中选择它,并将其设置为隐藏将其隐藏在选择选项中.
这是我的CodePen演示,它探索了其他选择框样式,并在浅色背景上显示了这个样式.
Fáb*_*lva 33
你应该看一下Tessa的答案,因为它只是CSS而且现在好多了!这个答案现在差不多已经有5年了,所以情况有所改变.我保留原来的答案仅供参考.
我更接近你需要的东西:
你需要使整个SELECT变灰(这样当它关闭时,它是灰色的),然后"un-grey"所有的OPTION(把它们变黑)和灰色的第一个孩子.像这样的东西:
CSS
select
{
color: #ccc;
}
option
{
color: #000;
}
option:first-child
{
color: #ccc;
}
Run Code Online (Sandbox Code Playgroud)
编辑 所以编辑的代码是:
HTML
<select onchange="changeMe(this)">
<option selected disabled>Please select your favourite fruit</option>
<option>Apple</option>
<option>Banana</option>
</select>
Run Code Online (Sandbox Code Playgroud)
使用Javascript
<script type="text/javascript">
function changeMe(sel)
{
sel.style.color = "#000";
}
</script>
Run Code Online (Sandbox Code Playgroud)
我更新了jsFiddle.您可以点击此处查看:http://jsfiddle.net/s5Xy2/5/
请注意,我还更改了HTML部分,因为我认为您要使用"禁用"属性(因此,您还必须添加"selected"属性).
如果您仍然需要纯CSS代码,请访问:http://jsfiddle.net/s5Xy2/4/
小智 5
灵感来自 Fábio Silva 的解决方案,这是一个使用AngularJS的非常酷的解决方案:
select {
color: #ccc;
}
option {
color: #aaa;
}
option:first-child {
color: #ccc;
}
select.ng-dirty {
color: #aaa;
}
Run Code Online (Sandbox Code Playgroud)