在自定义元素内附加自定义元素会导致隐藏元素

pbu*_*007 3 html javascript custom-element

为什么我无法将自定义元素附加到另一个自定义元素?好吧,我可以,但结果是子元素现在被隐藏了。我不明白,因为我没有将它附加到父级的影子 DOM 或其他东西中。

https://jsfiddle.net/qehoLf8k/1/

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

结果:看不到<my-text>内部<my-page>。我的意图是将任意数量的<my-text>元素附加到<my-page>元素中。

检查员形象

Emi*_*ier 5

因为您使用的是 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>
Run Code Online (Sandbox Code Playgroud)