首页 > 解决方案 > 在自定义元素中附加自定义元素会导致隐藏元素

问题描述

为什么我不能将自定义元素附加到另一个自定义元素?好吧,我可以,但结果是子元素现在被隐藏了。我不明白,因为我没有将它附加到父母的影子 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>元素中。

检查员形象

标签: javascripthtmlcustom-element

解决方案


因为您使用的是 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>

推荐阅读