为选择选项占位符设置字体颜色

新手上路,请多包涵

寻找一种方法来设置下拉列表占位符的字体颜色。当需要选择 id 时,以下工作:

 select:required:invalid {
    color: #9e9e9e;
}

但是,我不希望这些下拉列表是输入所必需的。一旦我删除了所需的标签,占位符字体就会变回黑色。

以下是我的下拉列表:

 <select id="searchresults4" name="primarysport">
    <option value="">Choose Primary Sport...</option>
    <option>Football</option>
    <option>Basketball</option>
    <option>Baseball</option>
    <option>Softball</option>
    <option>Soccer</option>
    <option>Golf</option>
</select>

原文由 Michael Philibin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

要直接解决 option 字体颜色,我们可以将 select 元素的颜色设置为浅灰色,然后将除第一个字体颜色之外的所有 option 颜色设置变黑。

这样,第一个 option 继承浅灰色,并显示为 select 既打开又关闭。

 select {
  color: #9e9e9e;
}
option:not(:first-of-type) {
  color: black;
}
 <select id="searchresults4" name="primarysport">
  <option value="">Choose Primary Sport...</option>
  <option>Football</option>
  <option>Basketball</option>
  <option>Baseball</option>
  <option>Softball</option>
  <option>Soccer</option>
  <option>Golf</option>
</select>

由于浅灰色字体颜色是通过在 select 元素上设置它来实现的,然后 :not 在设置 option 时否决它,当颜色为黑色时制作完成后,文字也会显示为灰色。

如果这是不可取的,我们可以根据 select 是否有 :focus 来更改颜色,当元素正在使用或未使用时显示灰色或黑色(取决于口味) :

 /* with the :focus here, we would show grey when not using the element */
select {
  color: black;
}
/* with the :focus here, we show grey when using the element */
select:focus {
  color: #9e9e9e;
}
option {
  color: black;
}
option:first-of-type {
  color: #9e9e9e;
}
 <select id="searchresults4" name="primarysport">
  <option value="">Choose Primary Sport...</option>
  <option>Football</option>
  <option>Basketball</option>
  <option>Baseball</option>
  <option>Softball</option>
  <option>Soccer</option>
  <option>Golf</option>
</select>

除了这些可能性之外:

尽管可以使用方法(包括以下方法)在 select 打开时隐藏初始/默认非值 (即“选择主要运动……”)但这可能不是理想的

注意: 一旦选择了 option ,在改变主意的情况下将无法返回到默认的非值初始状态。

然而,如果这种可用性/可访问性问题不是问题,这里有一个简单的修改,在 select` 打开时隐藏非值默认值:

 select {
  color: #9e9e9e;
}
option:not(:first-of-type) {
  color: black;
}
/* the modification */
option:first-of-type {
  display: none;
}
 <select id="searchresults4" name="primarysport">
  <option value="">Choose Primary Sport...</option>
  <option>Football</option>
  <option>Basketball</option>
  <option>Baseball</option>
  <option>Softball</option>
  <option>Soccer</option>
  <option>Golf</option>
</select>

原文由 Fred Gandt 发布,翻译遵循 CC BY-SA 4.0 许可协议

看这边…

 select:required:invalid {
  color: gray;
}
option[value=""][disabled] {
  display: none;
}
option {
  color: black;
}
 <select id="searchresults4" name="primarysport" required>
    <option value="" disabled selected>Choose Primary Sport...</option>
    <option>Football</option>
    <option>Basketball</option>
    <option>Baseball</option>
    <option>Softball</option>
    <option>Soccer</option>
    <option>Golf</option>
</select>

原文由 Ramon Marques 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题