You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改DOM元素并撤销更改?SVG元素修改还原实现问题

SVG元素修改后撤销改动的问题修复

你的撤销逻辑无法生效,核心原因是仅修改了局部变量的引用指向,没有实际替换DOM树中已经修改的元素:

  • 点击撤销按钮时,let element = elements.get(50)拿到的是指向DOM中已有元素的引用,后续element = copy只是让这个局部变量指向了你之前克隆的备份节点,既没有替换页面上实际渲染的元素,也没有更新存储元素的elements Map,所以页面不会有任何变化。
  • 原代码还遗漏了对button3元素的获取,会直接触发运行时报错。

修正后的完整代码

JavaScript 代码

const button1 = document.getElementById('button1');
const button2 = document.getElementById('button2');
const button3 = document.getElementById('button3');
const elements = new Map();
let copy;

button1.addEventListener('click', event => {
   const svgns = "http://www.w3.org/2000/svg",
      container = document.getElementById( 'cont' );
   for (let x = 0; x < 500; x += 50) {
      const circle = document.createElementNS(svgns, 'circle');
      circle.setAttributeNS(null, 'cx', x);
      circle.setAttributeNS(null, 'cy', x);
      circle.setAttributeNS(null, 'r', 50);
      circle.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 1px;' );
      elements.set(x, circle);
      container.appendChild(circle);   
   }
});

button2.addEventListener('click', event => {
   const element = elements.get(50);
   copy = element.cloneNode(true);
   element.style.fill = "red";
});

button3.addEventListener('click', event => {
   const original = elements.get(50);
   const container = document.getElementById('cont');
   // 用备份节点替换DOM中的原节点
   container.replaceChild(copy, original);
   // 更新Map中存储的元素引用,保证后续操作正常
   elements.set(50, copy);
});

HTML 代码

<button id="button1">生成元素</button>
<button id="button2">修改元素</button>
<button id="button3">撤销改动</button>

<svg id="cont" height="1000" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>

内容的提问来源于stack exchange,提问作者user14480036

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:06:02