blob: 0f1452497c728e0d0161d2736de7b3db4bf78aa1 (
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
|
---
title: Element.shadowRoot
slug: Web/API/Element/shadowRoot
tags:
- API
- DOM遍历
- ShadowRoot
translation_of: Web/API/Element/shadowRoot
---
<p>{{APIRef('Shadow DOM')}} {{SeeCompatTable}}{{draft}}</p>
<p><code>Element.shadowRoot</code> 是只读属性,表示元素挂载的shadow root。可以使用 {{domxref('Element.attachShadow')}} 给一个已存在的元素添加shadow root。</p>
<h2 id="Syntax" name="Syntax">语法</h2>
<pre class="syntaxbox">var <em>shadowroot =</em><em> element</em>.shadowRoot;
</pre>
<h3 id="值">值</h3>
<p>可以是一个{{domxref('ShadowRoot')}}实例对象,但如果一个shadow root的 {{domxref("ShadowRoot.mode", "mode")}}被设置为 <code>closed</code>那么它的值将会是 <code>null</code>。(详情请见 {{domxref("Element.attachShadow")}} ).</p>
<h2 id="示例">示例</h2>
<p>下面代码片段取自 <a href="https://github.com/mdn/web-components-examples/tree/master/life-cycle-callbacks">life-cycle-callbacks</a> (<a href="https://mdn.github.io/web-components-examples/life-cycle-callbacks">在线查看</a>), 在这个示例中我们创建了一个在元素属性中指定了大小和颜色的正方形元素。</p>
<p>在<code><custom-square></code>标签的class定义中我们在生命周期的回调函数里调用了一些外部方法——<code>updateStyle()</code>,正是这个函数使得我们添加的正方形元素可以改变大小和颜色。你可以看到我们将<code>this</code>(即我们创建的正方形元素本身)作为一个参数传入了这个方法。</p>
<pre class="brush: js">connectedCallback() {
console.log('Custom square element added to page.');
updateStyle(this);
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
updateStyle(this);
}
</pre>
<p>在<code>updateStyle()</code>函数中我们通过{{domxref("Element.shadowRoot")}}获取到了Shadow DOM引用。在这里我们利用了标准的DOM遍历技巧来获取在Shadow DOM中{{htmlelement("style")}}元素并更新了其中的CSS样式:</p>
<pre class="brush: js">function updateStyle(elem) {
const shadow = elem.shadowRoot;
const childNodes = Array.from(shadow.childNodes);
childNodes.forEach(childNode => {
if (childNode.nodeName === 'STYLE') {
childNode.textContent = `
div {
width: ${elem.getAttribute('l')}px;
height: ${elem.getAttribute('l')}px;
background-color: ${elem.getAttribute('c')};
}
`;
}
});
}</pre>
<p> </p>
<h2 id="标准">标准</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">标准</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
<tr>
<td>{{SpecName('Shadow DOM', '#widl-Element-attachShadow-ShadowRoot-ShadowRootInit-shadowRootInitDict', 'attachShadow()')}}</td>
<td>{{Spec2('Shadow DOM')}}</td>
<td>Initial definition.</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
{{Compat("api.Element.shadowRoot")}}
|