实现
export class ShadowDom extends HTMLElement {
public _shadow: ShadowRoot;
public _fragment: DocumentFragment;
constructor() {
super();
this._shadow = this.attachShadow({ mode: 'open' });
this._fragment = document.createDocumentFragment();
const config = { attributes: true };
const o = new MutationObserver(this.update);
o.observe(this, config);
}
update(mutationList, observer) {
[].slice.call(this.children).forEach((child) => this._fragment.appendChild(child));
this.shadowRoot!.appendChild(this._fragment);
}
}
使用
customElements.define('shadow-dom', ShadowDom);
<shadow-dom>
</shadow-dom>
生命周期
developer.mozilla.org/zh-CN/docs/…