使用 <template>
时是否可以将文本节点分配给插槽?和 <slot>
年代?
假设我有一个看起来像的模板
<template>
<span>
<slot name="mySlot"></slot>
</span>
</template>
我希望能够只向插槽添加文本,而不必添加 <span>
每次我使用模板时打开和关闭标签。这可能吗?如果不是纯 HTML,JavaScript 呢?最好只传递文本内容,这样在进入的过程中就不会应用任何样式。目前我使用的是无效标签
<n>
以避免这个问题。
最佳答案
当然,您可以使用 命令式插槽分配 ,但还没有在 Safari 中。
::slotted(*)
可以不是 目标文本节点。 <script>
customElements.define("slotted-textnodes", class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open',
slotAssignment: 'manual' // imperative assign only
}).innerHTML = `<style>::slotted(*){color:red}</style>
Click me! <slot name="title"></slot> <slot>NONE</slot>!!!`;
}
connectedCallback() {
let nodes = [], node;
setTimeout(() => { // wait till lightDOM is parsed
const nodeIterator = document.createNodeIterator(
this, NodeFilter.SHOW_TEXT, {
acceptNode: (node) => node.parentNode == this && (/\S/.test(node.data))
}
);
while ((node = nodeIterator.nextNode())) nodes.push(node);
this.onclick = (e) => {
this.shadowRoot.querySelector("slot:not([name])").assign(nodes[0]);
nodes.push(nodes.shift());
}
})
}
})
</script>
<slotted-textnodes>
Foo
<hr separator>Bar<hr separator>
<b>text INSIDE nodes ignored by iterator filter!</b>
Baz
<span slot="title">Can't mix Declarative and Imperative slots!!!</span>
</slotted-textnodes>
关于javascript - 文本节点可以开槽吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71706107/