CSS - 伪元素 - ::slotted()



::slotted() 伪元素表示具有 slot 属性的元素。与 ::part() 伪元素不同,::slotted() 伪元素仍然封装在 Web 组件的 <template> 中的 <style> 元素中。

此伪元素仅在 shadow DOM 内部的 CSS 中使用时才有效。

语法

selector::slotted(<compound-selector>) { /* ... */ }

CSS ::slotted 示例

这是一个 ::slotted() 伪元素的示例。在此示例中

  • 模板正在使用三个插槽。

  • 定义了一个自定义元素“sample-card”。

  • CSS 样式已添加到 <template> 内的 <style> 块中。

  • 插槽需要首先声明,使用类名或 ID。

  • 声明的插槽稍后在 html 代码中使用类名或 ID 调用。

  • 如果类名或 ID 标识符与声明的不匹配,则会呈现插槽的描述。

尝试更改类名或 ID 或样式,并查看更改后的效果。

Open Compiler
<html> <head> </head> <body> <template id="sample-template"> <style> ::slotted(.p-text) { background-color: lavender; } h2::slotted(.heading) { background: silver; } ::slotted(#footer-text) { background-color: lightsteelblue; border: 2px solid black; } </style> <div> <h2><slot name="heading">title goes here</slot></h2> <slot name="p-text">content goes here</slot> <slot name="footer-text">Footer here</slot> </div> </template> <sample-card> <span class="heading" slot="heading">::Slotted Example</span> <p class="p-text" slot="p-text">Paragraph text</p> <p id="footer-text" slot="footer-text">Footer text</p> </sample-card> <script> customElements.define( 'sample-card', class extends HTMLElement { constructor() { super(); const template = document.getElementById('sample-template'); const shadow = this.attachShadow({ mode: 'open' }); shadow.appendChild(template.content.cloneNode(true)); const elementStyle = document.createElement('style'); elementStyle.textContent = ` div { width: 250px; border: 5px inset green; border-radius: 2px; padding: 5px; }`; shadow.appendChild(elementStyle); const cssTab = document.querySelector('#css-output'); const editorStyle = document.createElement('style'); editorStyle.textContent = cssTab.textContent; shadow.appendChild(editorStyle); cssTab.addEventListener('change', () => { editorStyle.textContent = cssTab.textContent; }); } }, ); </script> </body> </html>
广告