::slotted() - CSS(层叠样式表) 编辑
:slotted()
CSS 伪元素 用于选定那些被放在 HTML模板 中的元素 (更多请查看 使用模板和插槽).
这个伪类选择器仅仅适用于 影子节点树(Shadow Dom). 并且只会选择实际的元素节点, 而不包括文本节点.
/* Selects any element placed inside a slot */
::slotted(*) {
font-weight: bold;
}
/* Selects any <span> placed inside a slot */
::slotted(span) {
font-weight: bold;
}
语法
::slotted( <compound-selector-list> )where
<compound-selector-list> = <compound-selector>#
where
<compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!
where
<type-selector> = <wq-name> | <ns-prefix>? '*'
<subclass-selector> = <id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector>
<pseudo-element-selector> = ':' <pseudo-class-selector>
<pseudo-class-selector> = ':' <ident-token> | ':' <function-token> <any-value> ')'where
<wq-name> = <ns-prefix>? <ident-token>
<ns-prefix> = [ <ident-token> | '*' ]? |
<id-selector> = <hash-token>
<class-selector> = '.' <ident-token>
<attribute-selector> = '[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'where
<attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='
<attr-modifier> = i | s
样例
下面的小片段是关于 插槽伪类元素 小demo (点击查看实例).
在这个小demo 中, 我们使用一个带有3个插槽的HTML模板:
<template id="person-template">
<div>
<h2>Personal ID Card</h2>
<slot name="person-name">NAME MISSING</slot>
<ul>
<li><slot name="person-age">AGE MISSING</slot></li>
<li><slot name="person-occupation">OCCUPATION MISSING</slot></li>
</ul>
</div>
</template>
自定义元素 <person-details>
的定义如下:
customElements.define('person-details',
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById('person-template');
let templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'});
let style = document.createElement('style');
style.textContent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' +
'h2 { margin: 0 0 10px; }' +
'ul { margin: 0; }' +
'p { margin: 10px 0; }' +
'::slotted(*) { color: gray; font-family: sans-serif; } ';
shadowRoot.appendChild(style);
shadowRoot.appendChild(templateContent.cloneNode(true));
}
})
为了更好地区分未被成功填充的插槽和成功填充的插槽, 我们在CSS中选择了所有的插槽元素(::slotted(*)
), 并填充了不一样的颜色和字体. 结果也是如此.
元素就像如下被填充了起来:
<person-details>
<p slot="person-name">Dr. Shazaam</p>
<span slot="person-age">Immortal</span>
<span slot="person-occupation">Superhero</span>
</person-details>
规范
Specification | Status | Comment |
---|---|---|
CSS Scoping Module Level 1 ::slotted | Working Draft | Initial definition. |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.参考
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论