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

使用JavaScript修改SVG后页面不更新 手动重贴才正常显示

问题原因

SVG元素属于http://www.w3.org/2000/svg命名空间,直接使用document.createElement()创建的是默认HTML命名空间下的元素,浏览器不会将其识别为可渲染的SVG节点,因此即使插入到DOM中也不会显示图形。你通过开发者工具剪切粘贴SVG时,浏览器会自动修正节点的命名空间,所以图形可以正常渲染。

修复方法

创建SVG和其子元素时,统一使用document.createElementNS()方法并指定SVG命名空间即可。

修正后完整代码

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
  <script type="text/javascript">
    const SVG_NS = 'http://www.w3.org/2000/svg';
    var valuesi = new Int32Array(256);
    var values = new Float32Array(valuesi.length);
    crypto.getRandomValues(valuesi);
    var svg = document.createElementNS(SVG_NS, "svg");
    svg = document.body.appendChild(svg);
    var width = 500,
      height = 500;
    svg.setAttribute("width", width);
    svg.setAttribute("height", height);
    var circle, radius = 5;
    for (var i = valuesi.length - 1; i > 0; --i) {
      values[i] = valuesi[i] / 2147483648;
    }
    for (var i = values.length - 1; i > 0; --i) {
      circle = document.createElementNS(SVG_NS, "circle");
      circle = svg.appendChild(circle);
      circle.setAttribute("cx", width / 2 + values[i] * width / 2);
      --i;
      circle.setAttribute("cy", height / 2 + values[i] * height / 2);
      circle.setAttribute("r", radius);
      circle.setAttribute("fill", "black");
    }
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:05