Med*_*ist 2 javascript web-component
是否可以将head和body作为 Web 组件的元素包含在内?
我尝试了下面的示例,但web-html放置在body内,而head为空:
索引.html:
<!doctype html>
<html>
<web-html></web-html>
<script type="module" src="html.js"></script>
</html>
Run Code Online (Sandbox Code Playgroud)
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));
};
});
Run Code Online (Sandbox Code Playgroud)
自定义元素必须包含在<head>或 元素中<body>。因此它不应该包含任何<head>or<body>元素。
因此,如果您想在两者上都包含内容<head>,则<body>需要以不同的方式进行:document.head.appendChild()例如。
此外,<head>和<body>必须是 的直接子元素<html>,因此您不能将它们包含在自定义元素中。