【发布时间】:2022-12-28 18:08:08
【问题描述】:
我正在使用 Shadow DOM 处理 customElement,例如:
<hello-there><b>S</b>amantha</hello-there>
而 innerHTML(在我的例子中由 lit/lit-element 生成)是这样的:
<span>Hello <slot></slot>!</span>
我知道,如果 const ht = document.querySelector('hello-there') 我可以调用 .innerHTML 并获得 <b>S</b>amantha 并且在 ht 的 shadowRoot 上,我可以调用 .innerHTML 并获得 <span>Hello <slot></slot>!</span>。但...
如果我已经表达(没有 ShadowDOM)HTML <span>Hello <b>S</b>amantha!</span>,那么浏览器基本上向读者呈现等价物。除了遍历所有 .assignedNodes 并将插槽内容替换为插槽之外,还有其他方法可以获得此输出吗?像.slotRenderedInnerHTML这样的东西?
(更新:我现在已经编写了确实遍历 assignedNodes 并做我想做的代码,但与浏览器原生解决方案相比,它看起来脆弱且缓慢。)
class HelloThere extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = '<span>Hello <slot></slot>!</span>';
}
}
customElements.define('hello-there', HelloThere);
<hello-there><b>S</b>amantha</hello-there>
<div>Output: <input type="text" size="200" id="output"></input></div>
<script>
const ht = document.querySelector('hello-there');
const out = document.querySelector('#output');
</script>
<button onclick="out.value = ht.innerHTML">InnerHTML hello-there</button><br>
<button onclick="out.value = ht.outerHTML">OuterHTML hello-there</button><br>
<button onclick="out.value = ht.shadowRoot.innerHTML">InnerHTML hello-there shadow</button><br>
<button onclick="out.value = ht.shadowRoot.outerHTML">OuterHTML hello-there shadow (property does not exist)</button><br>
<button onclick="out.value = '<span>Hello <b>S</b>amantha!</span>'">Desired output</button>
【问题讨论】:
-
ht.shadowRoot.innerHTML你要买什么?为什么需要删除slot标签? -
请按 StackOverflow 编辑器中的 [ <> ] 按钮并创建可执行文件 SO sn-p。
-
@Danny'365CSI'Engelman——完成了。
-
@connexo——我正在查看带有在浏览器中显示的插槽标签的输出。
-
再一次:为什么你需要移除插槽标签?你得到的结果是您的浏览器呈现的内容。这就是时隙机制的工作原理。
标签: web-component shadow-dom custom-element lit