CSS :selected pseudo class similar to :checked, but for lt;optiongt; elements(CSS :selected 伪类类似于 :checked,但用于 lt;optiongt;元素)
问题描述
有没有办法在 <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
所以,这个 CSS 可以工作,尽管在每个浏览器中都无法设置 color
样式:
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>
要在 close 下拉列表中设置当前选定选项的样式,您可以尝试颠倒逻辑:
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>元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CSS :selected 伪类类似于 :checked,但用于 <op


基础教程推荐
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01