diff --git a/packages/icons/src/svg/load.ts b/packages/icons/src/svg/load.ts index 1557467ff..59098bdbe 100644 --- a/packages/icons/src/svg/load.ts +++ b/packages/icons/src/svg/load.ts @@ -13,10 +13,28 @@ function parseSvg(svgData: string): IconifyIconStructure { const xmlDoc = parser.parseFromString(svgData, 'image/svg+xml'); const svgElement = xmlDoc.documentElement; + // 提取 SVG 根元素的关键样式属性 + const getAttrs = (el: Element, attrs: string[]) => + attrs + .map((attr) => + el.hasAttribute(attr) ? `${attr}="${el.getAttribute(attr)}"` : '', + ) + .filter(Boolean) + .join(' '); + + const rootAttrs = getAttrs(svgElement, [ + 'fill', + 'stroke', + 'fill-rule', + 'stroke-width', + ]); + const svgContent = [...svgElement.childNodes] .filter((node) => node.nodeType === Node.ELEMENT_NODE) .map((node) => new XMLSerializer().serializeToString(node)) .join(''); + // 若根有属性,用一个 g 标签包裹内容并继承属性 + const body = rootAttrs ? `${svgContent}` : svgContent; const viewBoxValue = svgElement.getAttribute('viewBox') || ''; const [left, top, width, height] = viewBoxValue.split(' ').map((val) => { @@ -25,7 +43,7 @@ function parseSvg(svgData: string): IconifyIconStructure { }); return { - body: svgContent, + body, height, left, top,