From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../zh-cn/web/css/_colon_host-context()/index.html | 92 ++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 files/zh-cn/web/css/_colon_host-context()/index.html (limited to 'files/zh-cn/web/css/_colon_host-context()/index.html') diff --git a/files/zh-cn/web/css/_colon_host-context()/index.html b/files/zh-cn/web/css/_colon_host-context()/index.html new file mode 100644 index 0000000000..69168913ff --- /dev/null +++ b/files/zh-cn/web/css/_colon_host-context()/index.html @@ -0,0 +1,92 @@ +--- +title: ':host-context()' +slug: 'Web/CSS/:host-context()' +translation_of: 'Web/CSS/:host-context()' +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +
+

:host-context() CSS 伪类的作用是选择shadow DOM 中shadow host,这个伪类内可以写关于该shadow host的CSS规则。 (我们可以从 shadow DOM 中选择一个自定义元素 custom element) — 但前提是,在DOM 层级中,括号中的选择器参数必须和shadow host 的祖先相匹配。

+
+ +

典型的使用方法是后代选择器表达式。例如 h1   — 只选择在<h1> 内的自定义元素的实例。

+ +
+

Note: 该伪类的css样式在 shadow DOM 之外的元素上是没有效果的

+
+ +
/* 选择了一个 shadow root host, 当且仅当这个
+ shadow root host 是括号中选择器参数(h1)的后代 */
+
+:host-context(h1) {
+  font-weight: bold;
+}
+
+:host-context(main article) {
+  font-weight: bold;
+}
+
+ +

Syntax

+ +
{{CSSSyntax}}
+ +

Examples

+ +

下边的代码片段来自 host-selectors (这里查看样式效果)。

+ +

在本例中,我们有一个简单的自定义元素 — <context-span> — 你可以把文字包裹在该自定义标签中:

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

在自定义元素的构造器函数中,我们创建 style 和 span 元素。让 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-context(h1) { font-style: italic; } 和 :host-context(h1):after { content: " - no links in headers!" 这些CSS 规则规定了位于<h1> 标签内部的 <context-span> 元素的实例的样式。

+ +

Specifications

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

Browser compatibility

+ + + +

{{Compat("css.selectors.host-context")}}

+ +

See also

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