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

标签 javascript html custom-element

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

Inspector image

最佳答案

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

关于javascript - 在自定义元素内附加自定义元素会导致隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472960/

相关文章:

javascript - 无需电线传递的同构 hyperHTML 组件

javascript - 使用 $.get 从另一个页面加载元素对根元素不起作用?

html - 自定义元素名称可以包含 Unicode 吗?

javascript - CustomElements 在 Firefox 中无法使用大约 :config properties enabled

javascript - 将鼠标悬停在工具提示上时保持 v-tooltip 打开

javascript - Knockout.js - 停止在 foreach 循环中重新渲染元素

html - iOS 7 中的视口(viewport)单位错误

javascript - Twitter Bootstrap 选项卡在 IE8 中不工作

html - 如何在 Logo css 下显示文本

javascript - 关于自定义 Web 组件和生命周期回调的说明