首页 > 解决方案 > 带有阴影的自定义元素不渲染

问题描述

我正在尝试使用阴影制作自定义元素,但是当我添加阴影时,元素的内容不会呈现。这是我的代码:

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”

标签: javascripthtmlshadow-domcustom-element

解决方案


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

如果要显示 Light DOM 内容,<slot>请在 Shadow DOM 中使用。

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>


推荐阅读