JavaScript创建的SVG在Firefox检查器可见但页面不显示
问题原因及解决办法
你的rect元素能在DOM检查器中看到却无法显示,核心问题是错误地给SVG常规属性使用了带命名空间的setAttributeNS方法。
SVG的普通属性(比如x、y、width、height、stroke这类)不属于任何命名空间,不需要通过setAttributeNS设置。你给这些属性都传入了svgNS作为命名空间参数,导致浏览器无法正确识别属性值,因此无法渲染出rect元素。
修复后的代码
把所有setAttributeNS(svgNS, ...)替换成setAttribute(...)即可:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> </style> <title>xyz</title> </head> <body> <div> <svg id="mysvg" xmlns="http://www.w3.org/2000/svg" width="360" height="360"> <line x1="1" y1="1" x2="359" y2="359" stroke="black"/> <circle cx="100.00" cy="100.00" r="25.17" fill="#00ffff" stroke="red"/> </svg> </div> </body> <script> const svgNS = "http://www.w3.org/2000/svg"; let svg_el = document.getElementById("mysvg"); let sh_el = document.createElementNS(svgNS, "rect"); // 改用setAttribute设置常规属性,无需命名空间 sh_el.setAttribute("x", "150"); sh_el.setAttribute("y", "150"); sh_el.setAttribute("stroke", "blue"); sh_el.setAttribute("width", "10"); sh_el.setAttribute("height", "40"); // 可选:显式设置填充为透明,仅显示边框 sh_el.setAttribute("fill", "none"); svg_el.appendChild(sh_el); </script> </html>
如果一定要保留setAttributeNS写法,将第一个参数改为null(表示无命名空间)也能生效:
sh_el.setAttributeNS(null, "x", "150"); sh_el.setAttributeNS(null, "y", "150"); // 其他属性同理
内容的提问来源于stack exchange,提问作者M Wade
相关产品推荐
相关产品推荐

