附加到Web组件内的阴影后,使用JS创建的模板标签不会出现

Dav*_*lsh 2 javascript web-component shadow-dom html5-template

我希望以下代码创建一个元素,其中包含一个div带有文本“ Hi” 的元素。

该元素出现在检查器中,但屏幕上看不到任何文本。

当我将模板从a更改template为a时,div将显示文本。我在这里做错了什么?

class MyComponent extends HTMLElement {
    constructor() {
        super()

        const shadowRoot = this.attachShadow({ mode: 'open' })
        const template = document.createElement('template')
        const div = document.createElement('div')

        div.innerHTML = 'Hi'
        template.appendChild(div)

        shadowRoot.appendChild(template.content)
    }
}
customElements.define('my-component', MyComponent)
Run Code Online (Sandbox Code Playgroud)

Sup*_*arp 5

<template> 是一个特殊的元素。

通过其content属性附加一些HTML元素:

template.content.appendChild(div)
Run Code Online (Sandbox Code Playgroud)

或通过其innerHTML属性添加HTML代码:

template.innerHTML = '<div>Hi</div>'
Run Code Online (Sandbox Code Playgroud)

  • 是。实际上,“内容”是一个DocumentFragment (2认同)