影子 DOM 隐藏了 innerHTML。

3
当使用影子DOM创建自定义元素并设置元素的innerHTML时,它不会被显示。为什么?是否有方法可以防止这种情况发生?
//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>
1个回答

6
为什么?这是 Shadow DOM 的主要特性之一:使用新的 DOM(称为 Shadow DOM)来遮盖/恢复初始 DOM(称为 light DOM)。
阅读更多有关 Google 的 Shadow DOM 简介
为了防止这种情况发生:
- 如果您不需要它们,请勿使用 Shadow DOM。您可以创建没有 Shadow DOM 的自定义元素。 - 使用 <slot> 将所有或部分 light DOM 插入 Shadow 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接