【问题标题】:How can I add children to the shadow DOM in HTML?如何在 HTML 中将子级添加到影子 DOM?
【发布时间】:2020-11-06 22:27:10
【问题描述】:

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

【问题讨论】:

    标签: native-web-component


    【解决方案1】:

    自定义元素中的 HTML with shadowDOMlightDOM

    中保持(不可见)

    你要么自己移动它:

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

    注意内容的样式!

    文本/html 保留在 lightDOM 中,它在 shadowDOM 中反映

    请阅读:::slotted CSS selector for nested children in shadowDOM slot

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2015-07-10
      • 2016-05-29
      • 1970-01-01
      • 2018-08-19
      • 2022-01-23
      • 2012-02-24
      • 2015-09-23
      • 2018-05-10
      相关资源
      最近更新 更多