繁体   English   中英

有没有办法将 append svg 文件转换为 HTML?

[英]Is there a way to append svg file to HTML?

我的目标是 append <svg>来自./public/images/x.svg文件的元素。 问题是,我找不到 function 从文件创建元素。

我试过的:

  1. 当前解决方案:将d属性存储在AppendSVG.js文件中。
let svg = document.createElementNS("http://www.w3.org/2000/svg","svg")
svg.setAttributeNS(null,"height", "16")
svg.setAttributeNS(null, "width", "16")

let path = document.createElementNS("http://www.w3.org/2000/svg","path")
path.setAttributeNS(null, "d", "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z")

svg.appendChild(path)

document.getElementsByTagName("Body")[0].appendChild(svg)

x.svg

<svg height="16" width="16">
  <path d="M3.75 1.5a.25.25 0 00-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 00.25-.25V6h-2.75A1.75 1.75 0 019 4.25V1.5H3.75zm6.75.062V4.25c0 .138.112.25.25.25h2.688a.252.252 0 00-.011-.013l-2.914-2.914a.272.272 0 00-.013-.011zM2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0113.25 16h-9.5A1.75 1.75 0 012 14.25V1.75z"></path>
</svg>

fetch是解决方案

let src = "./public/x.svg"

fetch(src)
.then((response) => {
    if (!response.ok) {
        throw Error(`Request for ${src} returned ${response.status} ${response.statusText}`)
    }
    return response.text();
})
.then((body) => {
    console.log(body.toLowerCase().trim())
    if (!(body.startsWith("<svg"))) {
        throw Error(`Resource ${src} returned an invaldi SVG file`)
    }
    const parser = new DOMParser()
    const doc = parser.parseFromString(body, "text/html")
    const fragment = doc.querySelector("svg")
    if (fragment == null) {
        throw Error(`Document does not contain svg element`)
    }
    document.getElementsByTagName("body")[0].appendChild(fragment)
})

暂无
暂无

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

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