【问题标题】:Make First option as gray and other as black in Select [duplicate]在 Select [重复] 中将第一个选项设为灰色,将其他选项设为黑色
【发布时间】:2019-12-30 07:15:28
【问题描述】:

以下是我的代码,它在 Firefox 68.0.2 中运行良好,但在 Chrome 76 和 Safari 12.1.2 上运行良好。让我知道解决方法或我在这里做错了什么。

我想将第一个选择选项设为灰色,其余选项设为黑色。

代码-

$(document).ready(function(){

  $("select").change(function(){
    if ($(this).val()=="") $(this).css({color: "#aaa"});
    else $(this).css({color: "#000"});
  });
  
});	
select{
  color:#aaa;
}
option:not(first-child) {
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
	<option value="">Please select and option</option>
	<option>#1</option>
	<option>#2</option>
	<option>#3</option>
	<option>#4</option>
</select>

【问题讨论】:

标签: javascript html css


【解决方案1】:

option:first-childcolor 属性设为灰色,其他为黑色。像这样

$(document).ready(function(){

  $("select").change(function(){
    if ($(this).val()=="") $(this).css({color: "#aaa"});
    else $(this).css({color: "#000"});
  });
  
});	
select option { color: black; }
select option:first-child{
 color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
	<option value="">Please select and option</option>
	<option>#1</option>
	<option>#2</option>
	<option>#3</option>
	<option>#4</option>
</select>

【讨论】:

    【解决方案2】:

    更改 CSS

    select{
          color:#aaa;
        }
        option{
          color:#000;
        }
        option:first-child {
          color: #aaa;
        }
    

    $(document).ready(function(){
    
      $("select").change(function(){
        if ($(this).val()=="") $(this).css({color: "#aaa"});
        else $(this).css({color: "#000"});
      });
      
    });
    select{
      color:#aaa;
    }
    option{
      color:#000;
    }
    option:first-child {
      color: #aaa;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select>
    	<option value="">Please select and option</option>
    	<option>#1</option>
    	<option>#2</option>
    	<option>#3</option>
    	<option>#4</option>
    </select>

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多