【问题标题】:Custom element with shadow not rendering带有阴影的自定义元素不渲染
【发布时间】:2019-03-23 11:15:23
【问题描述】:

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

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”

【问题讨论】:

标签: javascript html shadow-dom custom-element


【解决方案1】:

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

如果要显示 Light DOM 内容,请在 Shadow DOM 中使用&lt;slot&gt;

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);
&lt;custom-element&gt;blah blah blah&lt;/custom-element&gt;

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 2020-11-24
    • 2017-07-15
    • 2011-04-11
    • 1970-01-01
    • 2019-03-28
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多