阴影 dom 隐藏 innerHTML

Shadow dom hides innerHTML

使用阴影 dom 创建自定义元素并设置元素的内部 HTML 时,它不会显示。为什么?有什么办法可以防止这种情况发生吗?

//JS代码

export default class VideoPlayer extends DomElement {
   constructor() {
      super();
      const mountPoint = document.createElement('div');
      this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
  }
}
window.customElements.define('video-player', VideoPlayer);

//HTML 代码

<video-player>Why is this text hidden?</video-player>

为什么?它是 Shadow DOM 的主要特征之一:对 mask/recover 最初的 DOM 称为 light DOM 有一个新的 DOM 叫做 Shadow DOM

阅读更多关于 Google 的 introduction to Shadow DOM

为了防止这种情况发生:

  • 如果不需要,请不要使用 Shadow DOM。您可以创建没有阴影的自定义元素 DOM.

  • 使用<slot>将所有光线DOM的一部分插入阴影DOM:

class VideoPlayer extends HTMLElement {
   constructor() {
      super();
      this.attachShadow({ mode: 'open' })
          .innerHTML = '<slot></slot>'
  }
}
window.customElements.define('video-player', VideoPlayer);
<video-player>Why is this text hidden?</video-player>