繁体   English   中英

Vanilla JS web 组件包括和

[英]Vanilla JS web component including <head> and <body>

是否可以将头部身体作为 web 组件的元素包含在内?

我尝试了下面的示例,但是web-html放在body内,而head是空的:

索引.html

<!doctype html>
<html>
    <web-html></web-html>
    <script type="module" src="html.js"></script>
</html>

html.js

customElements.define('web-html', class extends HTMLElement {
    constructor() {
        super();
        const template = document.createElement('template');
        template.innerHTML = `
            <head>
                <meta charset="utf-8" />
                <title> Index </title>
            </head>
            <body>
                <slot> ... </slot>
            </body>
        `;
        const shadowRoot = this.attachShadow({mode:'open'});
        shadowRoot.appendChild(template.content.cloneNode(true));
    };
});

自定义元素必须包含在<head><body>元素中。 因此它不应包含任何<head><body>元素。

因此,如果您想在<head><body>上都包含内容,则需要以不同的方式进行:例如使用document.head.appendChild()

此外, <head><body>必须是<html>的直接子元素,因此您不能将它们包含在自定义元素中。

Web 组件是 html 文档正文的一部分。 当你想在头脑中包含 somphing 时,你必须通过 dom api 来做到这一点。 但是你可以在不同的模板中做 head 的东西并将内容复制到 head 标签中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM