繁体   English   中英

通过 DOMParser SVG 命名空间将 SVG 字符串渲染到 DOM

[英]Render SVG string to DOM via DOMParser SVG namespace

我正在尝试从字符串中解析 SVG 元素并将其渲染到 DOM 中,但是当我解析为image/svg+xml时, <svg>以某种奇怪的方式附加到 DOM 中,不会渲染它(至少在火狐中)。 当我解析为text/html时,它会呈现但添加了一个不需要的xmlns属性。

有没有办法在渲染时仍然解析为image/svg+xml (因为它就是这样)? 我尝试了 document.adoptNode但没有帮助。

这不会呈现:

 const svg = '<svg viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.75 2a.75.75 0 0 1.75.75V7h4.25a.75.75 0 1 1 0 1.5H8.5v4.25a.75.75 0 1 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2z"/></svg>'; const parser = new DOMParser(); const doc = parser.parseFromString(svg, 'image/svg+xml'); document.body.appendChild(doc.documentElement);

这会呈现,但包含不需要的xmlns属性:

 const svg = '<svg viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.75 2a.75.75 0 0 1.75.75V7h4.25a.75.75 0 1 1 0 1.5H8.5v4.25a.75.75 0 1 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2z"/></svg>'; const parser = new DOMParser(); const doc = parser.parseFromString(svg, 'text/html'); document.body.appendChild(doc.body.firstChild);

The issues comes down to the xmlns attribute which is required when parsing for the SVG mime type but optional in the HTML one, as described in https://stackoverflow.com/a/18468348/808699 .

鉴于 SVG 被认为是 HTML 中的外来元素,如果想省略xmlns属性,最好将其解析为text/html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM