1. 思路
- 使用 cloneNode(true) 深拷贝节点及其子节点的结构
- 利用 computedStyle 获取当前节点的样式
- 遍历获取的样式结构体,赋值给复制节点
- 递归子节点,循环进行2-3步
2. 代码示例
function copyStyle(node: HTMLElement, targetNode: HTMLElement) {
const computedStyle = getComputedStyle(node);
Array.from(computedStyle).forEach((key) => targetNode.style.setProperty(
key,
computedStyle.getPropertyValue(key),
computedStyle.getPropertyPriority(key),
));
targetNode.style.pointerEvents = 'none';
for (let i = 0; i < node.children.length; i += 1) {
copyStyle(
node.children[i] as HTMLElement,
targetNode.children[i] as HTMLElement,
);
}
}
const shadowNode = currentNode.cloneNode(true) as HTMLElement;
copyNode(currentNode, shadowNode);
3. 实现效果