From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/css/_colon_host()/index.html | 90 ++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 files/zh-cn/web/css/_colon_host()/index.html (limited to 'files/zh-cn/web/css/_colon_host()/index.html') diff --git a/files/zh-cn/web/css/_colon_host()/index.html b/files/zh-cn/web/css/_colon_host()/index.html new file mode 100644 index 0000000000..7542ac2c81 --- /dev/null +++ b/files/zh-cn/web/css/_colon_host()/index.html @@ -0,0 +1,90 @@ +--- +title: ':host()' +slug: 'Web/CSS/:host()' +tags: + - ':host()' + - CSS + - Layout + - Pseudo-class + - RTeference + - Web +translation_of: 'Web/CSS/:host()' +--- +
{{seecompattable}}{{CSSRef}} 
+ +
CSS 伪类函数 :host() 选择包含使用这段 CSS 的 Shadow DOM 的影子宿主(这样就可以从 Shadow DOM 中选择包括它的自定义元素)——但前提是该函数的参数与选择的阴影宿主相匹配。
+ +

最简单的用法是仅将类名放在某些自定义元素实例上,然后将相关的类选择器作为函数参数包含在内。不能将它与后代选择器表达式一起使用,以仅选择特定祖先内部的自定义元素的实例。这是 {{cssxref(":host-context()")}} 的作用。

+ +
+

注意:在shadow DOM之外使用时,这没有任何效果。

+
+ +
/* 选择阴影根元素,仅当它与选择器参数匹配 */
+ :host(.special-custom-element) {
+   font-weight: bold;
+ }
+ +

句法

+ +
{{csssyntax}}
+ +

例子

+ + + +

以下片段取自我们的宿主选择器示例也可以观看在线演示)。

+ +

在这个例子中,有一个简单的自定义元素 <context-span> 可以用它包裹文本:

+ +
<h1>Host selectors <a href="#"><context-span>example</context-span></a></h1>
+ +

在元素的构造函数中,创建stylespan元素,填充span自定义元素的内容,并style使用一些 CSS 规则填充元素:

+ +
let style = document.createElement('style');
+let span = document.createElement('span');
+span.textContent = this.textContent;
+
+const shadowRoot = this.attachShadow({mode: 'open'});
+shadowRoot.appendChild(style);
+shadowRoot.appendChild(span);
+
+style.textContent = 'span:hover { text-decoration: underline; }' +
+                    ':host-context(h1) { font-style: italic; }' +
+                    ':host-context(h1):after { content: " - no links in headers!" }' +
+                    ':host-context(article, aside) { color: gray; }' +
+                    ':host(.footer) { color : red; }' +
+                    ':host { background: rgba(0,0,0,0.1); padding: 2px 5px; }';
+ +

:host(.footer) { color : red; } 规则为文档中所有在其上设置了 footer 类的<context-span> 元素实例(此实例中的影子宿主)设置样式——使用它来为 {{htmlelement("footer")}} 中的元素提供实例一种特殊的颜色。

+ +

产品规格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS Scope', '#host-selector', ':host()') }}{{ Spec2('CSS Scope') }}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("css.selectors.hostfunction")}}

+ +

也可以看看

+ + -- cgit v1.2.3-54-g00ecf