带样式的HTML节点深拷贝

带样式的HTML节点深拷贝

1. 思路

  1. 使用 cloneNode(true) 深拷贝节点及其子节点的结构
  2. 利用 computedStyle 获取当前节点的样式
  3. 遍历获取的样式结构体,赋值给复制节点
  4. 递归子节点,循环进行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. 实现效果

下方浅蓝色的即为复制的节点