0

例如,我希望能够用 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>
4

1 回答 1

0

带有shadowDOM的自定义元素中的 HTML 在lightDOM 中保持(不可见)

您要么自己移动它:

<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 SLOT

<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 中

请阅读:::slotted CSS 选择器,用于 shadowDOM 插槽中的嵌套子项

于 2020-11-13T15:22:28.960 回答