我在文本输入中使用占位符,效果很好。但我也希望在选择框中使用占位符。当然,我可以使用以下代码:

<select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>

但“选择您的选项”是黑色而不是浅灰色。所以我的解决方案可能是基于CSS的。jQuery也很好。

这只会使下拉列表中的选项变灰(因此单击箭头后):

option:first {
    color: #999;
}

问题是:人们如何在选择框中创建占位符?但这已经得到了回应,欢呼。

使用此选项会导致所选值始终为灰色(即使在选择实际选项后):

select {
    color: #999;
}

当前回答

如果使用的是Angular,请执行以下操作:

<选择><option[ngValue]=“undefined”disabled selected>选择您的选项</option><option[ngValue]=“hurr”>Durr</option></选择>

其他回答

这是我的贡献。火腿+咖啡脚本+SCSS

Haml

=f.collection_select :country_id, [us] + Country.all, :id, :name, {prompt: t('user.country')}, class: 'form-control'

咖啡脚本

  $('select').on 'change', ->
    if $(this).val()
      $(this).css('color', 'black')
    else
      $(this).css('color', 'gray')
  $('select').change()

SCSS

select option {
  color: black;
}

通过更改服务器代码和仅根据属性的当前值设置类样式,可以仅使用CSS,但这种方式似乎更简单、更干净。

$('select').on('change',function(){if($(this).val()){return$(this).css('color','black');}其他{return$(this).css('color','gray');}});$('select').change();选择选项{颜色:黑色;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><select class=“form control”name=“user[country_id]”id=“user_country_id”><option value=“”>国家</option><option value=“231”>美国</option><option value=“1”>安道尔</option>阿富汗</option><option value=“248”>津巴布韦</option></select>

您可以添加更多的CSS(选择选项:firstchild),以在占位符打开时保持其灰色,但我并不在乎这一点。

以下解决方案也适用于Firefox,无需任何JavaScript:

选项[默认值]{显示:无;}<选择><option value=“”默认选择>选择您的年龄</option><option value=“1”>1</option><option value=“2”>2</option><option value=“3”>3</option><option value=“4”>4</option></选择>

selected使页面加载时选择特定选项禁用可确保表单提交中排除该选项隐藏直观地隐藏下拉列表中的选项

<选择><option selected disabled hidden>选择选项</option><option>一个</option><option>两个</option><option>三个</option></选择>

HTML中有Cool属性,您可以使用它为select属性创建占位符在我的情况下,我使用以下代码,您可以根据您的要求更改它

 <select ref={relationship} required className="sellertype">
          <option value="" disabled selected hidden>Select Your Seller Type</option>
          <option value="1">Importer</option>
          <option value="2">Exporter</option>
          <option value="3">Local Seller</option>
          <option value="4">Local Buyer</option>
        </select>

现在“选择卖家类型”将作为占位符

JavaScript中的另一种可能性:

 $('body').on('change', 'select', function (ev){
    if($(this).find('option:selected').val() == ""){
        $(this).css('color', '#999');
        $(this).children().css('color', 'black');
    }
    else {
        $(this).css('color', 'black');
        $(this).children().css('color', 'black');
    }
});

JSFiddle公司