CSS 伪类 :host()函数允许您从其影子 DOM 内部选择自定义元素,但前提是作为函数参数给出的选择器(例如类选择器)与影子主机匹配。
在影子 DOM 之外使用时,伪类 :host() 函数不起作用。
语法
:host(<compound-selector>) {
/* ... */
}
选择影子主机,但前提是它与 selector 参数匹配。
:host(.special-custom-element) {
/* ... */
}
CSS :host-function 示例
以下示例演示如何使用 :host() 伪类函数来选择自定义元素的影子主机。在本例中,自定义元素是 context-span 元素 -
<html>
<head>
<style>
div {
font-size: 25px;
}
</style>
</head>
<body>
<div>
<p>QikepuCom CSS - <a href="#"><context-span class="custom-host">:host()</context-span></a></p>
</div>
<script>
class HostStyle extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
const styleElement = document.createElement('style');
styleElement.textContent = `
:host(.custom-host) {
color: blue;
background: pink;
}`;/*applies the styling to custom element if it matches the class selector .custom-host*/
shadowRoot.appendChild(styleElement);
const spanElement = document.createElement('span');
spanElement.textContent = this.textContent;
shadowRoot.appendChild(spanElement);
}
}
customElements.define('context-span', HostStyle);
</script>
</body>
</html>