我试图将第一个选项的颜色更改为灰色,只有文本(选择一个选项),但这里它不起作用:
.grey_color {
color: #ccc;
font-size: 14px;
}
Run Code Online (Sandbox Code Playgroud)
<select id="select">
<option selected="selected"><span class="grey_color">select one option</span></option>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option >five</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我的jsfiddle在这里是jsfiddle
Moh*_*eri 42
Suresh,你不需要在你的代码中使用任何东西.你需要的是这样的事情:
.others {
color:black
}
Run Code Online (Sandbox Code Playgroud)
<select id="select">
<option style="color:gray" value="null">select one option</option>
<option value="1" class="others">one</option>
<option value="2" class="others">two</option>
</select>
Run Code Online (Sandbox Code Playgroud)
但正如您所看到的,因为选项中的第一项是您的选择控件显示的第一项,您无法看到其指定的颜色.如果打开选择列表并查看打开的项目,您将看到可以为第一个选项指定灰色.所以你需要在jQuery中使用其他东西.
$(document).ready(function() {
$('#select').css('color','gray');
$('#select').change(function() {
var current = $('#select').val();
if (current != 'null') {
$('#select').css('color','black');
} else {
$('#select').css('color','gray');
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是我在jsFiddle中的代码.
小智 15
我最近遇到了同样的问题,我找到了一个非常简单的解决方案.
您所要做的就是将第一个选项设置为禁用和选中.像这样:
<select id="select">
<option disabled="disabled" selected="selected">select one option</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这将在加载页面时显示第一个选项(变灰).它还可以防止用户在单击列表后选择它.
你只需要添加disabled
的option
属性
<option disabled>select one option</option>
Run Code Online (Sandbox Code Playgroud)
这是我的 jQuery 演示
<!doctype html>
<html>
<head>
<style>
select{
color:#aaa;
}
option:not(first-child) {
color: #000;
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select").change(function(){
if ($(this).val()=="") $(this).css({color: "#aaa"});
else $(this).css({color: "#000"});
});
});
</script>
<meta charset="utf-8">
</head>
<body>
<select>
<option disable hidden value="">CHOOSE</option>
<option>#1</option>
<option>#2</option>
<option>#3</option>
<option>#4</option>
</select>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/monster75/cnt73375/1/