我想获取模板内容,将其注入带阴影DOM的自定义元素,并通过span
选择器将样式应用于template
::slotted
中,但这似乎没有按预期工作。
<!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()
中向light DOM添加一些内容。而是在connectedCallback()
方法中做到这一点。
当您在Developer控制台中查看Elements窗格时,您可以看到,当您向<slot>
和light DOM添加HTML片段或元素时,结果会有所不同。