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