且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更改< option>文本的颜色.在< select>中?

更新时间:2023-01-28 12:46:50

当然,您不需要在代码中使用任何内容. 您需要的就是这样:

Suresh, you don't need use anything in your codes. What you need is just something like this:

.others {
    color:black
}

<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>

但是如您所见,由于选项中的第一项是选择控件显示的第一件事,因此您看不到其分配的颜色.当您打开选择列表并看到打开的项目时,您会看到可以为第一个选项分配灰色. 因此,您还需要jQuery中的其他功能.

But as you can see, because your first item in options is the first thing that your select control shows, you can not see its assigned color. While if you open the select list and see the opened items, you will see you could assign a gray color to the first option. So you need something else in 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');
      }
   }); 
});

这是我在 jsFiddle 中的代码.