blob: a4e3da4c7cfe9ff628e72ef9ac4f43f02a860ba6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
---
title: ':host'
slug: 'Web/CSS/:host'
tags:
- ':host'
- CSS
- DOM
translation_of: 'Web/CSS/:host'
---
<div>{{ CSSRef }}</div>
<p><span class="seoSummary"><strong><code>:host</code></strong> CSS伪类选择包含其内部使用的CSS的shadow DOM的根元素 - 换句话说,这允许你从其shadow DOM中选择一个自定义元素。</span></p>
<div class="note">
<p><strong>注意:</strong>在shadow DOM之外使用时,这没有任何效果。</p>
</div>
<pre class="brush: css no-line-numbers">/* Selects a shadow root host */
:host {
font-weight: bold;
}
</pre>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">{{csssyntax}}</pre>
<h2 id="示例">示例</h2>
<p>以下片段取自我们的 <a href="https://github.com/mdn/web-components-examples/tree/master/host-selectors">host-selectors </a>示例(<a href="https://mdn.github.io/web-components-examples/host-selectors/">在线演示</a>)。</p>
<p>在这个例子中,我们有一个简单的自定义元素 — <code><context-span></code> — 你可以包裹文本:</p>
<pre class="brush: html"><h1>Host selectors <a href="#"><context-span>example</context-span></a></h1>
</pre>
<p>在元素的构造函数中,我们创建<code>style</code>和<code>span</code>元素,用自定义元素的内容填充<code>span</code>,并使用一些CSS规则填充<code>style</code> 元素:</p>
<pre class="brush: js">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; }';
</pre>
<p><code>:host { background: rgba(0,0,0,0.1); padding: 2px 5px; }</code> 规则设置<code><context-span></code>元素的所有实例的样式(此实例中为影子根元素)的所有实例。</p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ SpecName('CSS Scope', '#host-selector', ':host') }}</td>
<td>{{ Spec2('CSS Scope') }}</td>
<td>Initial definition.</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility" name="Browser_compatibility">浏览器兼容</h2>
<div>
<p>{{Compat("css.selectors.host")}}</p>
</div>
<h2 id="参见">参见</h2>
<ul>
<li><a href="/en-US/docs/Web/Web_Components">Web components</a></li>
<li>{{cssxref(":host()")}}</li>
<li>{{cssxref(":host-context()")}}</li>
</ul>
|