html - CSS :selected pseudo class similar to :checked, 但对于 <option> 元素

标签 html css css-selectors pseudo-class

有没有办法为当前选择的 <option> 设置样式? <select> 中的元素元素?

然后我可以为当前选定的选项元素提供背景颜色吗?这样我就可以设置当前在关闭的下拉列表中可见的选项的样式。

最佳答案

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes

来源:w3.org


因此,尽管 color 的样式在所有浏览器中都不可能,但此 CSS 有效:

option:checked { color: red; }

一个实际的例子,从下拉列表中隐藏当前选择的元素。

option:checked { display:none; }
<select>
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>


要在已关闭 下拉列表中设置当前所选选项的样式,您可以尝试反转逻辑:

select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */

关于html - CSS :selected pseudo class similar to :checked, 但对于 <option> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8619406/

相关文章:

javascript - 从 javascript 打印 iframe 在终端服务器上的 IE 中不起作用

javascript - 向下滚动时在顶部浏览器中以固定模式制作 div

css - 垂直居中的嵌套 flex 盒子

css - 不寻常的 CSS 选择器

css - :active css selector not working for IE8 and IE9

java - 使用 jsoup 获取元素外部但元素旁边的文本

php - 如何通过 HTML/CSS 使图片响应于 wordpress 自定义帖子类型

html - 如何在不破坏行的情况下创建表格? ( Bootstrap )

css - 跨浏览器兼容性的导航填充不同

html - 空 href 和 :link pseudo class 的奇怪结果