【问题标题】:How can I add child elements to a custom element in HTML markup?如何将子元素添加到 HTML 标记中的自定义元素?
【发布时间】:2019-04-16 18:21:28
【问题描述】:

我想创建一个能够在其中托管任何 HTML 标记的自定义元素:

<my-custom-element>
  <p>This is some message.</p>
  <div><button>Click here</button></div>
</my-custom-element>

上面的标记似乎不起作用。每个浏览器都将其呈现为:

<my-custom-element></my-custom-element>
  <p>This is some message.</p>
  <div><button>Click here</button></div>

如何让自定义元素在标记中包含子元素?

【问题讨论】:

标签: javascript html web-component custom-element


【解决方案1】:

如果您使用的是 shadowDOM,那么您需要将 &lt;slot&gt; 添加到您的 shadowDOM 中。

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'}).innerHTML = '<style>:host{border:1px dashed red;display:inline-block;}</style><slot></slot>';
  }
}

customElements.define('my-element', MyElement);
<my-element>
  <p>This is some message.</p>
  <div><button>Click here</button></div>
</my-element>

【讨论】:

    【解决方案2】:

    使用connectedCallback事件

    customElements.define('my-element', class extends HTMLElement{
       constructor(){
          super();
       }
       connectedCallback(){
          this.innerHTML="<p>This is some message.</p><div><button>Click here</button></div>";
          // or this.appendChild(...)
       }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      相关资源
      最近更新 更多