如何将子元素添加到 HTML 标记中的自定义元素?
How can I add child elements to a custom element in HTML markup?
我想创建一个能够承载任何 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>
如何让自定义元素在标记中包含子元素?
如果您使用的是 shadowDOM,那么您需要将 <slot>
添加到您的 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>
使用 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(...)
}
});
我想创建一个能够承载任何 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>
如何让自定义元素在标记中包含子元素?
如果您使用的是 shadowDOM,那么您需要将 <slot>
添加到您的 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>
使用 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(...)
}
});