CSS :host-context() 伪类选择器允许您根据自定义元素在 DOM 中的使用位置,根据其祖先元素的类或属性,以不同的方式设置自定义元素的样式。
:host-context() 伪类函数在影子 DOM 之外使用时不起作用。
语法
:host-context(<compound-selector>) {
/* ... */
}
Firebox 和 Safari 浏览器不支持 :host-context()。
CSS :host-context 示例
以下示例演示了如何使用 :host-context() 伪类根据 DOM 中的上下文对自定义元素进行不同的样式设计 -
<html>
<head>
<style>
div {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<h3>QikepuCom CSS - <a href="#"><context-span>:host-context()</context-span></a></h3>
<p>CSS <context-span>:host-context()</context-span> pseudo-class selector allows you to style a custom element differently depending on where it is used in the DOM, based on the classes or attributes of its ancestor elements.</p>
</div>
<script>
class HostContext extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
const styleElement = document.createElement('style');
styleElement.textContent = `
:host-context(div) {
color: blue;
background-color: violet;
border: 3px solid red;
}
:host-context(div)::after {
content: ":host-context()";
}`;
shadowRoot.appendChild(styleElement);
}
}
customElements.define('context-span', HostContext);
</script>
</body>
</html>