将 <template> 中的内容注入 <slot>

Inject content from <template> into <slot>

我想获取模板内容,将其注入到带有阴影 DOM 的自定义元素中,并通过 ::slotted 选择器将样式应用于 template 内的 span 但这并没有' 似乎按预期工作。

<!doctype html>
<html lang="en">
    <head>
        <template id="template">
            <span>element from template</span>
        </template>
    </head>
    <body>
        <script type="text/javascript">
            class WithShadowDom extends HTMLElement {
                constructor() {
                    super();
                    const shadowRoot = this.attachShadow({mode: 'open'});
                    shadowRoot.innerHTML = `
                        <style>
                            ::slotted(span) {
                                font-size: 25px;
                            }
                        </style>
                    `;
                    shadowRoot
                        .appendChild(document.createElement('slot'))
                        .appendChild(
                            document.getElementById('template').content.cloneNode(true)
                        );
                }
            }
            window.customElements.define('with-shadow-dom', WithShadowDom);
            const myCustomElement = document.createElement('with-shadow-dom');
            document.body.appendChild(myCustomElement);
        </script>
    </body>
</html>

下面的部分没有按预期工作。 font-size css 未应用。

shadowRoot
    .appendChild(document.createElement('slot'))
    .appendChild(document.getElementById('template').content.cloneNode(true));

当直接在自定义元素中附加子 span 时,font-size 被应用。

const span = document.createElement('span');
span.innerHTML = 'asdffad';
shadowRoot
    .appendChild(document.createElement('slot'))
    .appendChild(span);

您已将跨度附加到阴影 dom。如果您希望将其插入 <slot> 位置,则应将其添加到灯 dom 中。

connectedCallback() {
    //template content
    this.appendChild(document.getElementById('template').content.cloneNode(true));
    //span element
    const span = document.createElement('span');
    span.innerHTML = 'asdffad';
    this.appendChild(span);
}

注意:您不应将某些内容附加到 constructor() 中的灯 DOM。而是在 connectedCallback() 方法中进行。

当您查看开发人员控制台中的 Elements 窗格时,您可以看到将 HTML 片段或元素添加到 <slot> 和光 DOM.