下面的代码不显示CategoryElement的子元素—只显示<>元素在暗影根。我如何使CategoryElement的子渲染?
<html>
<head>
</head>
<body>
<script>
class CategoryElement extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.header = document.createElement('p');
this.header.innerText = 'Shadow Header';
this.shadowRoot.append(this.header);
}
}
customElements.define('category-element', CategoryElement);
var elem = document.createElement('category-element');
document.body.appendChild(elem);
var outer = document.createElement('p');
outer.innerText = 'Outer Header';
elem.appendChild(outer);
</script>
</body>
<html>
我相信这能让你明白,但无论如何我都不是影子王国专家。
我添加了.shadowRoot
,如下所示:
elem.shadowRoot.appendChild(outer);
当我用开发工具检查时,我可以看到两个<p>
都在影子根元素(如果这是正确的引用方式)。
</head>
<body>
<script>
class CategoryElement extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
});
this.header = document.createElement('p');
this.header.innerText = 'Shadow Header';
this.shadowRoot.append(this.header);
}
}
customElements.define('category-element', CategoryElement);
var elem = document.createElement('category-element');
document.body.appendChild(elem);
var outer = document.createElement('p');
outer.innerText = 'Outer Header';
elem.shadowRoot.appendChild(outer);
</script>
</body>
<html>