如何在HTML标记中将子元素添加到自定义元素?

问题描述 投票:0回答:1

我想创建一个能够在其中托管任何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 html5 web-component custom-element
1个回答
0
投票

如果你使用的是shadow DOM,那么你需要在shadowDOM中添加一个qazxsw poi。

<slot>
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);
© www.soinside.com 2019 - 2024. All rights reserved.