【发布时间】:2019-07-18 01:58:51
【问题描述】:
我想获取模板内容,将其注入到带有阴影 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);
【问题讨论】:
标签: javascript web-component shadow-dom custom-element html-templates