JavaScript创建SVG元素不显示,直接写HTML标签可正常运行是什么原因
问题原因及解决方案
核心错误点
你使用document.createElement()创建SVG元素的方式不符合规范,SVG属于XML命名空间下的元素,不属于HTML原生DOM的命名空间范围,JS动态创建时必须手动指定SVG命名空间,浏览器才会将其识别为可渲染的图形元素。直接写在HTML文件中时浏览器会自动识别SVG命名空间,所以可以正常显示。
具体修改点
- 替换元素创建方法:不能用普通的
createElement,必须用createElementNS指定SVG命名空间 - 修复循环变量声明问题:原代码中
setAttributes方法的循环变量attribut没有加声明,会泄露为全局变量,需补充let - 可选优化:给SVG元素增加宽高属性,避免默认渲染尺寸不符合预期
修复后完整可运行代码
function setAttributes(node, attributes){ // 补充循环变量声明避免全局污染 for (let attribut in attributes){ node.setAttribute(attribut, attributes[attribut]); } } function createIconToParent(parentNode, error){ // 固定SVG命名空间,所有SVG元素都要使用这个命名空间创建 const SVG_NS = 'http://www.w3.org/2000/svg'; let svgTag = document.createElementNS(SVG_NS, 'svg'); let pathTag = document.createElementNS(SVG_NS, 'path'); setAttributes(svgTag, { "aria-hidden" : "true", "focusable" : "false", "data-prefix" : "fas", "role" : "img", "viewBox" : "0 0 512 512", // 可选:指定渲染宽高 "width": "24", "height": "24" }); if (error == true){ setAttributes(svgTag, { "data-icon" : "exclamation-circle", "class" : "svg-inline--fa fa-exclamation-circle fa-w-16" }); setAttributes(pathTag, { "fill" : "#08c708", "d" : "M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z" }); } else { setAttributes(svgTag, { "data-icon" : "check-circle", "class" : "svg-inline--fa fa-check-circle fa-w-16" }); setAttributes(pathTag, { "fill" : "crimson", "d" : "M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z" }); } svgTag.appendChild(pathTag); parentNode.appendChild(svgTag); } createIconToParent(document.body, true);
内容的提问来源于stack exchange,提问作者alexis wandor
相关产品推荐
相关产品推荐

