javascript - Shadow dom 隐藏 innerHTML

标签 javascript innerhtml web-component shadow-dom custom-element

当使用 shadow 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>

最佳答案

为什么?它是 Shadow DOM 的主要特征之一:使用名为 Shadow DOM 的新 DOM 屏蔽/恢复名为 light DOM 的初始 DOM .

阅读有关 Google 的更多信息 introduction to 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>

关于javascript - Shadow dom 隐藏 innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51284954/

相关文章:

javascript - 使用什么来代替 document.write 或 InnerHTML?

polymer 1.0 : <iron-meta> usage

javascript - 如何让 Web 组件使用 TypeScript 为 IE11/Edge/Chrome/Firefox 编译?

javascript - IF 语句多个答案 - 相同结果 Javascript

javascript - 我想在 javascript 中使用 window.getComputedStyle() 获取字体大小,但它不能

javascript - 跟踪和统计 Firebase 调用

javascript - 使用 Web 组件而不注册为自定义元素?

javascript - 删除 Discover Meteor Book 中的 URL 字段

javascript - document.getElementById ('AnyName' ).innerHTML = 内容在 IE 或 Safari 中不起作用,但在 Chrome 和 Firefox 中起作用

Mootools 请求更改 JavaScript 代码?