简体   繁体   English

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

[英]How can I add child elements to a custom element in HTML markup?

I want to create a custom element that's able to host any HTML markup within:我想创建一个自定义元素,它能够在以下内容中承载任何 HTML 标记:

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

The above markup doesn't seem to work.上面的标记似乎不起作用。 Every browser renders it like:每个浏览器都将其呈现为:

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

How can I have a custom element contain child elements in markup?如何让自定义元素在标记中包含子元素?

Use connectedCallback event使用 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(...)
   }
});

If you are using shadowDOM then you need to add a <slot> into your shadowDOM. 如果您使用的是shadowDOM,则需要在shadowDOM中添加<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); 
 <my-element> <p>This is some message.</p> <div><button>Click here</button></div> </my-element> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM