CSS:selected伪类类似于:checked,但对于< option>元素 [英] CSS :selected pseudo class similar to :checked, but for <option> elements
问题描述
是否可以在< select>
元素中设置当前选定的< option>
元素的样式?
Is there a way to style the currently selected <option>
element in a <select>
element?
然后我可以为当前选择的选项元素提供背景颜色吗?这样,我就可以设置关闭下拉菜单中当前可见的选项的样式.
I could then give a background color to the currently selected option element? That way I can style the option that's currently viewable in the closed dropdown.
推荐答案
:checked
伪类最初适用于具有HTML4selected
和checked
属性
the
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
来源: w3.org
因此,尽管并非在所有浏览器中都可以设置 color
的样式,但此CSS还是可以的:
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
此操作的一个示例,它从下拉列表中隐藏了当前选中的项目.
An example of this in action, hiding the currently selected item from the drop down list.
option:checked { display:none; }
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
要在 closed 下拉菜单中为当前选定的选项设置样式,您可以尝试反转逻辑:
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */
这篇关于CSS:selected伪类类似于:checked,但对于< option>元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!