gpt4 book ai didi

javascript - 如何克隆 ShadowRoot?

转载 作者:技术小花猫 更新时间:2023-10-29 12:12:12 26 4
gpt4 key购买 nike

我正在尝试克隆影子根,以便我可以交换 <content></content> 的实例及其相应的分布式节点。

我的方法:

var shadowHost = document.createElement('div');
var shadowRoot = shadowHost.createShadowRoot();

var clonedShadowRoot = shadowRoot.cloneNode(true);

不起作用,因为“ShadowRoot 节点不可克隆。”

这样做的动机是我希望检索组合影子树,以便我可以使用呈现的 HTML 标记。

由于 Shadow DOM 的性质,这可能不起作用,对分布式节点的引用可能会被克隆过程破坏。

组成影子树很可能是一个原生功能,但通过搜索 w3c 规范,我无法找到这样的方法。

有这样的native方法吗?或者,如果失败,手动遍历(在此过程中复制树)是否可行?

最佳答案

如果您尝试深度克隆可能包含一个或多个嵌套影子树的节点,那么您将需要从该节点遍历 DOM 树并沿途检查影子根。如果对先前的答案感兴趣,请参阅编辑历史记录,该答案表明浅克隆有缺陷的方法。

const deepClone = (host) => {
const cloneNode = (node, parent) => {
const walkTree = (nextn, nextp) => {
while (nextn) {
cloneNode(nextn, nextp);
nextn = nextn.nextSibling;
}
};

const clone = node.cloneNode();
parent.appendChild(clone);
if (node.shadowRoot) {
walkTree(node.shadowRoot.firstChild, clone.attachShadow({ mode: 'open' }));
}

walkTree(node.firstChild, clone);
};

const fragment = document.createDocumentFragment();
cloneNode(host, fragment);
return fragment;
};

// Example use of deepClone...

// create shadow host with nested shadow roots for demo
const shadowHost = () => {
const host = document.createElement('div');
const nestedhost = document.createElement('p');
nestedhost.attachShadow({mode: 'open'}).appendChild(document.createElement('span'));
host.attachShadow({mode: 'open'}).appendChild(nestedhost);
return host;
};

// return fragment containing deep cloned node
const fragment = deepClone(shadowHost());
// deep cloned node
console.log(fragment.firstChild);
// shadow tree node
console.log(fragment.firstChild.shadowRoot.firstChild);
// nested shadow tree node
console.log(fragment.firstChild.shadowRoot.firstChild.shadowRoot.firstChild);

关于javascript - 如何克隆 ShadowRoot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com