<selectedcontent>: 选定选项显示元素
<selectedcontent> HTML 元素用于在 <select> 元素内显示其当前选定的 <option> 元素的内容,该内容将显示在其第一个子 <button> 元素中。这使您能够自定义 <select> 元素的全部部分,也称为“可自定义的 selects”。
属性
此元素包含全局属性。
描述
您将 <selectedcontent> 元素用作 <button> 元素的唯一子元素,而该 <button> 元素必须是 <select> 元素的第一个子元素。任何 <option> 元素(<select> 的其他唯一有效子元素)必须出现在 <button> 和嵌套的 <selectedcontent> 对之后。
<select>
<button>
<selectedcontent></selectedcontent>
</button>
<option></option>
...
</select>
<selectedcontent> 的后台工作原理
<selectedcontent> 元素包含当前选定 <option> 元素内容的一个克隆。浏览器使用 cloneNode() 来渲染此克隆。当选定的 <option> 更改时(例如,在 change 事件期间),<selectedcontent> 的内容将被新选定 <option> 的克隆替换。了解此行为很重要,尤其是在处理动态内容时。
警告:由于浏览器仅在选定的 <option> 更改时才更新 <selectedcontent>,因此在 <select> 渲染后对选定 <option> 内容进行的任何动态修改都不会克隆到 <selectedcontent>。您需要手动更新 <selectedcontent>。如果您使用的流行前端 JavaScript 框架会在初始渲染后动态更新 <option> 元素,请注意——结果可能与您在 <selectedcontent> 中期望的不符。
<selectedcontent> 的惰性
默认情况下,<select> 元素中的任何 <button> 都处于 惰性 (inert) 状态。因此,该按钮内的所有内容(包括 <selectedcontent>)也处于惰性状态。这意味着用户无法与 <selectedcontent> 内的内容进行交互或聚焦。
使用 CSS 为选定选项的内容设置样式
您可以定位当前选定的 <option> 元素的内容,并设置其在 select 按钮中显示的方式。设置按钮的样式不会影响克隆的 <option> 内容的样式。这允许您自定义选定选项在按钮中的外观,而与它们在下拉列表中的外观分开。
例如,您的 <option> 元素可能包含图标、图像甚至视频,它们在下拉列表中可以很好地渲染,但可能导致 select <button> 变大、看起来杂乱并影响周围的布局。通过定位 <selectedcontent> 中的内容,您可以隐藏按钮中的元素(如图像),而不会影响它们在下拉列表中的显示方式,如下面的代码片段所示:
selectedcontent img {
display: none;
}
注意:如果 <button> 和/或 <selectedcontent> 元素未包含在 <select> 中,浏览器会创建一个隐式的 <button> 来显示选定 <option> 的内容。此回退按钮无法使用 button 或 selectedcontent 类型选择器通过 CSS 进行定位。
示例
您可以在我们的 可自定义 select 元素指南中找到包含 <selectedcontent> 元素的完整示例。
技术摘要
| 内容类别 | None |
|---|---|
| 允许内容 | 镜像选定 <option> 元素的内容。 |
| 标签省略 | 无,起始标签和结束标签都必须存在。 |
| 允许父级 | 一个 <button> 元素,它是 <select> 元素的第一个子元素。 |
| 隐式 ARIA 角色 | None |
| 允许的 ARIA 角色 | None |
| DOM 接口 | HTMLSelectedContentElement |
规范
| 规范 |
|---|
| HTML # the-selectedcontent-element |
浏览器兼容性
加载中…
另见
<select>元素<option>元素<optgroup>元素- 可定制的 select 元素