在 v1 影子根中,我们可以收听 slotchange
上<slot>
元素然后使用 slot.assignedNodes()
来检测变化。我正在寻找一种方法来使用 v0 影子根来做到这一点。
使用 ShadowDOM v0,有没有办法观察 <content>
的分布式节点的变化影子根中的元素?
实现这一点的最简单方法是使用 requestAnimationFrame
创建一个调用 content.getDistributedNodes()
的轮询循环将新结果与旧结果进行比较,但显然轮询并不理想,而且成本高昂。
如何做到这一点?
最佳答案
我和你几乎同时需要这个东西。我最终为此创建了一个库,我已经在测试中使用了一周左右的时间。该库名为content-change 。它对我来说效果很好,但我确信还有很多改进的机会。
它的工作原理是这样的;与 Shadow DOM v1 中 slot
元素的 slotchange
事件类似:
// Because this is non-spec, specify internally which components get to be watched
// "this" is the host element
ContentChange.watch(this);
const contentElement = shadow.querySelector('someContentSelector');
contentElement.addEventListener('contentchange', e => {
// React to distributed node changes for this content element
});
返回到监听器的事件
在event.details
中包含一些不同的类型。 event.details.type
将是以下三个之一:
“已添加节点”
“节点已删除”
“突变”
让您对不同的场景使用react。例如,当添加到主机元素的节点满足分发到该内容元素的要求时,您将收到以下内容:
{
"type": "nodesAdded",
"nodesAdded": [Nodes] // An array of newly distributed nodes
}
关于javascript - 我们如何观察 v0 影子根上的分布变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880512/