问题描述
为什么不能将自定义元素附加到另一个自定义元素?好吧,我可以,但是结果是子元素现在被隐藏了。我不明白,因为我没有将其附加到父母的影子DOM之类的东西上。
https://jsfiddle.net/qehoLf8k/1/
HTML
<template id="text">
<style>
.text {
color:red;
}
</style>
<div class="text">Hello</div>
</template>
<template id="page">
<style>
:host {
border:5px solid green;
display: block;
margin:20px;
height:100px;
width:100px;
}
</style>
This is a page
</template>
<div id="my-body"></div>
JS
class Text extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: 'open'});
const template = document.getElementById('text');
const node = document.importNode(template.content,true);
this.shadowRoot.appendChild(node);
}
}
customElements.define('my-text',Text);
class Page extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: 'open'});
const template = document.getElementById('page');
const node = document.importNode(template.content,true);
this.shadowRoot.appendChild(node);
}
}
customElements.define('my-page',Page);
const body = document.getElementById('my-body')
const page = document.createElement('my-page')
const text = document.createElement('my-text')
// Not working,element is hidden
page.appendChild(text)
body.appendChild(page)
// Working
//body.appendChild(text)
结果:无法看到<my-text>
中的<my-page>
。我的意图是将任意数量的<my-text>
元素添加到<my-page>
元素中。
解决方法
由于使用的是Shadow DOM,因此应使用<slot>
元素来指示子项在模板中的位置。否则,阴影将不知道该如何处理这些孩子,并且不会以视觉方式呈现它们。
<template id="page">
<style>
:host {
border:5px solid green;
display: block;
margin:20px;
height:100px;
width:100px;
}
</style>
<slot></slot> <!-- children go here -->
This is a page
</template>