簡體   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