2017-07-05 59 views
0

我想将第一个选项的颜色更改为#ccc,其他则保持#000,但它不起作用。为什么?谢谢。 我不想使用更改功能,我认为这是不必要的。如何根据特定选项更改文字颜色?

是这样的: enter image description here

HTML:

<select id="continent"> 
     <option value="-1">continent</option> 
     <option value="1">US</option> 
     <option value="2">UK</option> 
    </select> 

JS:

$("#continent option[value='-1']").css('color','#ccc'); 
+0

改变功能是必要的你将如何知道选择一个没有改变功能? – guradio

+0

只是第一个选项的颜色不是选择的 –

+0

添加内联样式但颜色只适用于选项'' – guradio

回答

1

$("#continent").change(function(){ 
 
    $("#continent").val() == "-1" ? $("#continent").css("color", "red") : $("#continent").css("color", "blue"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="continent"> 
 
    <option value="-1">continent</option> 
 
    <option value="1">US</option> 
 
    <option value="2">UK</option> 
 
</select>

记住预设默认选项

+0

谢谢,你的作品效果最好。 –

1

这里的颜色是溶液

$('.mySelect').change(function() { 
    if($(this).find("option:selected").attr("value")==2){ 
    $(this).find('option:selected').css('color', 'red'); 
    }else{ 
    $(this).find('option:selected').css('color', 'blue'); 
    } 

}); 

在上面的代码中,我使用.find()方法,其用于选择元件的选择子try this code in fiddle

1

为什么你要使用jQuery?这可以用纯CSS完成。

#continent option { 
 
    background-color: white; /* on XFCE the default background-color is #CCC! */ 
 
}
<select id="continent"> 
 
    <option value="-1" style="color:#cccccc">continent</option> 
 
    <option value="1">US</option> 
 
    <option value="2">UK</option> 
 
</select>

但是你可能不应该这样做,因为它看起来像选项被禁用,但事实并非如此。这违反直觉并违反可用性。

除此之外,它在其他操作系统上看起来不同。这是从上面的代码片段看起来像在Ubuntu与XFCE:

enter image description here

这是另一种解决方案是什么样子,如果选择了第一个选项也改变了<select>的颜色为浅灰色:

enter image description here

这就是为什么您应该使用<option value="-1" disabled>或另一种颜色。