阴影不渲染的自定义元素



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

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>

但它呈现的只是文本"你好世界">

这是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>

最新更新