gpt4 book ai didi

html - 类似于 :valid or :checked for select tags? 的 CSS 伪选择器

转载 作者:太空狗 更新时间:2023-10-29 16:05:42 25 4
gpt4 key购买 nike

我正在尝试寻找一种非 JavaScript 方式来设置 select 标记的样式如果它具有已选择的值。

例如,如果我有以下标签:

<select>
<option value="">Select a widget...</option>
<option value="1">Widget 1</option>
</select>

是否有 CSS 选择器可用于判断该选择标记的值何时不为空?

最佳答案

根据 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元素只有在用户选择时才会变得有效一个值。到那时它将继续处于 invalid 状态。


:valid:invalid 伪选择器本身可以帮助根据值是否已选择与否取决于几个因素。它们如下:

  • 通过选择,您的意思是检查是否选择了一个有效值,而不仅仅是任何选择。
  • 无效 值(在本例中为“选择一个小部件...”)具有 value="" 并且是选择元素下的第一个选项。
  • select 元素是一个强制元素 - 也就是说,我们可以向它添加 required 属性。

根据您的问题陈述,我认为您的场景满足上述所有因素。

select {
border: 2px solid blue;
outline: none;
}
select:valid {
border: 2px solid green;
outline: none;
}
<select required>
<option value="">Select a widget...</option>
<option value="1">Widget 1</option>
</select>

以上代码段已在 IE10+(包括 Edge)、Chrome、Opera 和 Firefox 中验证。

关于html - 类似于 :valid or :checked for select tags? 的 CSS 伪选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34935177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com