0

我正在使用 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>amanthaht 的 shadowRoot ,我可以调用.innerHTML Hello !`。但...

浏览器本质上呈现<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>

4

0 回答 0