JS动态创建SVG路径失败求助:无法生成目标关闭按钮SVG
动态生成关闭按钮SVG失败的解决办法
我尝试用JavaScript动态生成如下SVG,但代码无法正常运行:
<svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"> <path d="m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z"/> </svg>
我目前的尝试代码:
let closeButton = document.createElement("svg"); closeButton.setAttribute("height", "48"); closeButton.setAttribute("width", "48"); let closeButtonPath = document.createElementNS('http://www.w3.org/2000/svg',"path"); closeButtonPath.setAttributeNS(null, "d", "m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z"); closeButton.appendChild(closeButtonPath); this.#form.appendChild(closeButton);
问题原因
SVG属于XML命名空间规范下的元素,所有SVG相关标签都必须通过createElementNS指定http://www.w3.org/2000/svg命名空间来创建。你之前只给<path>元素用了命名空间,但<svg>元素用了普通的document.createElement(),导致浏览器无法正确识别这是SVG元素,自然无法渲染。
修正后的代码
// 给svg元素也指定SVG命名空间 let closeButton = document.createElementNS('http://www.w3.org/2000/svg', "svg"); closeButton.setAttribute("height", "48"); closeButton.setAttribute("width", "48"); let closeButtonPath = document.createElementNS('http://www.w3.org/2000/svg', "path"); closeButtonPath.setAttributeNS(null, "d", "m12.45 37.65-2.1-2.1L21.9 24 10.35 12.45l2.1-2.1L24 21.9l11.55-11.55 2.1 2.1L26.1 24l11.55 11.55-2.1 2.1L24 26.1Z"); closeButton.appendChild(closeButtonPath); this.#form.appendChild(closeButton);
内容的提问来源于stack exchange,提问作者Harry Stuart
相关产品推荐
相关产品推荐

