CSS伪选择器类似于:valid或:选中select标签?

我试图找到一种非JavaScript方式来设置选择标记的样式,如果它具有已选择的值.

例如,如果我有以下标记

是否有一个CSS选择器,我可以用来判断该select标签的值何时为空?

最佳答案
按照HTML5 Specs

The required attribute is a boolean attribute. When specified,the user will be required to select a value before submitting the form.

Constraint validation: If the element has its required attribute specified,and either none of the option elements in the select element’s list of options have their selectedness set to true,or the only option element in the select element’s list of options with its selectedness set to true is the placeholder label option,then the element is suffering from being missing.

If the value of the first option element in the select element’s list of options (if any) is the empty string,and that option element’s parent node is the select element (and not an optgroup element),then that option is the select element’s placeholder label option.

重点是我的

上述陈述暗示具有required属性的select元素仅在用户选择值时才有效.在此之前它将继续处于无效状态.

:有效,:无效的伪选择器本身可以帮助设置一个选择元素的样式,具体取决于是否选择了一个值,但它取决于几个因素.它们如下:

>通过选择,您的意思是检查是否已选择有效值而不是任何选择.
>无效值或空值(在本例中为“选择窗口小部件…”)具有值=“”并且是select元素下的第一个选项.
> select元素是必需元素 – 意思是,我们可以为其添加必需的属性.

根据您的问题陈述,我认为您的方案满足所有上述因素.

select {
  border: 2px solid blue;
  outline: none;
}
select:valid {
  border: 2px solid green;
  outline: none;
}