带有阴影的自定义元素未渲染

Custom element with shadow not rendering

我正在尝试制作一个带有阴影的自定义元素,但是当我添加阴影时,元素的内容没有呈现。这是我的代码:

JavaScript:

class CustomElement extends HTMLElement {
 constructor (){
  super();
  var shadow = this.attachShadow({mode: 'open'});
  var content = document.createElement("DIV");
  content.innerText = "hello world";
  shadow.appendChild(content);
 }
}
customElements.define("custom-element", CustomElement);

HTML:

<custom-element>blah blah blah</custom-element>

但它呈现的只是文本 "hello world"

这是阴影 DOM 的正常行为:阴影 DOM 内容掩盖了原始内容(称为光 DOM)。

如果要显示光 DOM 内容,请在阴影 DOM 中使用 <slot>

class CustomElement extends HTMLElement {
 constructor (){
  super();
  var shadow = this.attachShadow({mode: 'open'});
  var content = document.createElement("DIV");
  content.innerHTML = "hello world: <br> <slot></slot>";
  shadow.appendChild(content);
 }
}
customElements.define("custom-element", CustomElement);
<custom-element>blah blah blah</custom-element>