【问题标题】:Change the 'option' color with the attribute 'disabled'使用“禁用”属性更改“选项”颜色
【发布时间】:2020-05-07 17:59:27
【问题描述】:

我想用属性disabled 更改<option> 的字体颜色。

我试过了

option:disabled { color: red }

还有这个

option[disabled] { color: red }

两者都有效,但只有在您单击选择字段时颜色才会变为红色。默认情况下它是黑色的。怎么改?

这里是一个例子:http://jsfiddle.net/y0g0stbb/

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    不能同时选中和禁用。

    option:disabled {
      color: red;
    }
    <select>
      <option selected>Choose something</option>
      <option disabled>1</option>
      <option>2</option>
      <option>3</option>
    </select>

    如果你想禁用选择,而不是你需要将禁用的选项移动到选择标签

    select:disabled {
      color: red;
    }
    <select disabled>
      <option selected>Choose something</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
    </select>

    【讨论】:

      【解决方案2】:

      试试这个:

      CSS:

          select{
          color:red;
          }
          option{
          color:black;
          }
      

      【讨论】:

      • 可以选择禁用的。
      【解决方案3】:

      颜色必须应用于select 元素,而不是option。所以,你可以这样做:

      您可以使用required 并将空值分配给第一个选项:

      <select required>
          <option value="" disabled>0</option>
          <option value="1">1</option>
      </select>
      

      css:

      select:invalid { color: red; }
      

      If you do this, when the option with empty value is selected, the select element will be invalid, and so the above css class will tr​​igger.

      感谢这个帖子的回答解决了这个问题:Changing the color of a <select> depending on its value - CSS only(?)

      【讨论】:

        【解决方案4】:

        试试这个,希望它会工作: 在html中:

            <select>
              <option value="">Choose something</option>
               <option disabled="disabled" value="" class="red">1</option>
               <option disabled="disabled" value="" class="red">2</option>
               <option disabled="disabled" value="" class="red">3</option>
            </select>
        

        在 CSS 中:

           select :disabled.red{
           color: red;
           }
        

        【讨论】:

          【解决方案5】:

          如果没有选定的有效选项,您可以使用一点 Javascript 执行以下操作:

          <select class="">[options]</select>
          

          如果有一个选定的有效选项,您只需在 select 元素中通过 javascript 放置一些类:

          <select class="selected">[options]</select>
          

          然后在你的 CSS 中:

          select{
           color: [not selected color];
          }
          select.selected{
           color: [selected color];
          }
          

          【讨论】:

            猜你喜欢
            • 2019-07-14
            • 1970-01-01
            • 2011-07-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-13
            相关资源
            最近更新 更多