如何用纯JavaScript创建Material Icon?生成后元素存在但图标不显示如何解决
问题原因
- 核心问题:SVG及其子元素属于独立的XML命名空间,直接使用
document.createElement创建的svg、path等元素会被浏览器判定为普通HTML元素,不会触发SVG渲染逻辑,这是图标不显示的最主要原因。 - 次要问题1:svg样式设置存在错误冗余代码
svg.style.flexShrink = "inlineBlock",flexShrink属性值应为数字,该行代码无效。 - 次要问题2:未给svg设置
viewBox属性,也未给path设置fill填充色,也会影响渲染效果。
解决方案
将SVG相关元素的创建方法改为带命名空间的createElementNS,补充必要属性、删除无效代码即可,修改后的完整代码如下:
const iconBox = document.createElement("div"); iconBox.style.width = "28px"; iconBox.style.cursor = "pointer"; iconBox.style.display = "flex"; iconBox.style.opacity = "1"; iconBox.style.position = "relative"; iconBox.style.alignItems = "center"; iconBox.style.justifyContent = "center"; iconBox.style.backgroundColor = "#ffffff"; // 修改:使用命名空间创建svg元素 const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); // 补充viewBox属性 svg.setAttribute("viewBox", "0 0 24 24"); svg.style.width = "1em"; svg.style.height = "1em"; // 删除了无效的flexShrink: inlineBlock 代码 svg.style.transition = "fill 200ms"; svg.style.flexShrink = "0"; svg.style.userSelect = "none"; svg.style.fontSize = "2.1875rem"; // 修改:使用命名空间创建path元素 const path = document.createElementNS("http://www.w3.org/2000/svg", "path"); // 补充fill填充色 path.setAttribute("fill", "#000"); path.setAttribute( "d", "M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" ); svg.appendChild(path); iconBox.appendChild(svg); const container = document.getElementById("container"); container.appendChild(iconBox); console.log(container, "container");
内容的提问来源于stack exchange,提问作者Satoru Kikuchi
相关产品推荐
相关产品推荐

