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

时间:2019-03-23 11:15:23

标签: javascript html shadow-dom custom-element

我试图用阴影制作一个自定义元素,但是当我添加阴影时,该元素的内容无法渲染。这是我的代码:

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”

1 个答案:

答案 0 :(得分:2)

这是Shadow DOM的正常行为:Shadow DOM内容会掩盖原始内容(称为Light DOM)。

如果要显示Light DOM内容,请在Shadow 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>