文本节点可以开槽吗?
Can a text node be slotted?
使用 <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>
使用 <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>