如何将 children 添加到 HTML 中的影子 DOM?
How can I add children to the shadow DOM in HTML?
例如,我希望能够在HTML中这样写:
<my-container>
Some text.
</my-container>
JS:
class MyContainer extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({mode: 'open'})
const p = document.createElement('p')
shadow.appendChild(p)
}
}
customElements.define('my-container', MyContainer)
我最终得到的结果(虽然并不意外):
<my-container>
<p></p>
Some text.
</my-container>
我想要的:
<my-container>
<p>Some text.</p>
</my-container>
HTML 在自定义元素中 with shadowDOM 在 lightDOM[=42= 中保持(不可见) ]
你要么自己搬:
<my-element>
Hello World, I came from lightDOM
</my-element>
<script>
customElements.define("my-element", class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
}); // sets and returns thi.shadowRoot for free
this.wrapper = this.shadowRoot.appendChild(document.createElement('H1'));
this.wrapper.innerHTML = "please click me";
}
connectedCallback() {
this.onclick = () => this.wrapper.innerHTML = this.innerHTML;
}
});
</script>
或者你使用 shadowDOM SLOTs
<style>
my-element{
color:green;
}
</style>
<my-element>
Hello World, I am REFLECTED from lightDOM
</my-element>
<script>
customElements.define("my-element", class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
}); // sets and returns thi.shadowRoot for free
this.wrapper = this.shadowRoot.appendChild(document.createElement('H1'));
this.wrapper.innerHTML = "<slot></slot";
}
connectedCallback() {
}
});
</script>
注意内容的样式!
text/html在 lightDOM 中保持,在 shadowDOM
中反射
请阅读:
例如,我希望能够在HTML中这样写:
<my-container>
Some text.
</my-container>
JS:
class MyContainer extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({mode: 'open'})
const p = document.createElement('p')
shadow.appendChild(p)
}
}
customElements.define('my-container', MyContainer)
我最终得到的结果(虽然并不意外):
<my-container>
<p></p>
Some text.
</my-container>
我想要的:
<my-container>
<p>Some text.</p>
</my-container>
HTML 在自定义元素中 with shadowDOM 在 lightDOM[=42= 中保持(不可见) ]
你要么自己搬:
<my-element>
Hello World, I came from lightDOM
</my-element>
<script>
customElements.define("my-element", class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
}); // sets and returns thi.shadowRoot for free
this.wrapper = this.shadowRoot.appendChild(document.createElement('H1'));
this.wrapper.innerHTML = "please click me";
}
connectedCallback() {
this.onclick = () => this.wrapper.innerHTML = this.innerHTML;
}
});
</script>
或者你使用 shadowDOM SLOTs
<style>
my-element{
color:green;
}
</style>
<my-element>
Hello World, I am REFLECTED from lightDOM
</my-element>
<script>
customElements.define("my-element", class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
}); // sets and returns thi.shadowRoot for free
this.wrapper = this.shadowRoot.appendChild(document.createElement('H1'));
this.wrapper.innerHTML = "<slot></slot";
}
connectedCallback() {
}
});
</script>
注意内容的样式!
text/html在 lightDOM 中保持,在 shadowDOM
中反射请阅读: