尝试使用 .innerHTML 添加 SVG 数据



我正在尝试使用element.innerHTML动态创建SVG元素,但它似乎不起作用。

这是我要使用的 SVG 数据:

<style type="text/css">
.st0{fill:url(#SVGID_1_);}
.st1{fill:#F4F4F4;}
</style>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="50" y1="6.5" x2="50" y2="88.19">
<stop  offset="0" style="stop-color:#F8615F"/>
<stop  offset="1" style="stop-color:#C1272D"/>
</linearGradient>
<path class="st0" d="M69.5,40.2L69.5,40.2C50.1,74,51.3,85.1,51.1,87.2c0,0,0,0.1,0,0.1c-0.1,0.5-0.5,0.9-1,0.9s-1-0.4-1-0.9
c0,0,0-0.1,0-0.1c-0.2-2.1,0.9-13.2-18.5-47h0c-1.9-3.3-3-7.1-3-11.2C27.5,16.6,37.6,6.5,50,6.5S72.5,16.6,72.5,29
C72.5,33.1,71.4,36.9,69.5,40.2z"/>
<circle class="st1" cx="50" cy="29.1" r="10.4"/>

这是 HTML:

<svg id="scene" viewBox="0 0 1000 1000">
<g id = "locations">
</g>
</svg>

而 JavaScript:

function createLocation(px, py, video_id = "")
{
var locations = document.getElementById("locations");
var loc = document.createElement("g");
loc.setAttribute("id", "loc_" + video_id);
loc.innerHTML = '<style type="text/css"> n.st0{fill:url(#SVGID_1_);} n.st1{fill:#F4F4F4;} n</style>n <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="50" y1="6.5" x2="50" y2="88.19"> n<stop  offset="0" style="stop-color:#F8615F"></stop>n<stop  offset="1" style="stop-color:#C1272D"></stop> n</linearGradient> n<path class="st0" d="M69.5,40.2L69.5,40.2C50.1,74,51.3,85.1,51.1,87.2c0,0,0,0.1,0,0.1c-0.1,0.5-0.5,0.9-1,0.9s-1-0.4-1-0.9nc0,0,0-0.1,0-0.1c-0.2-2.1,0.9-13.2-18.5-47h0c-1.9-3.3-3-7.1-3-11.2C27.5,16.6,37.6,6.5,50,6.5S72.5,16.6,72.5,29nC72.5,33.1,71.4,36.9,69.5,40.2z"></path> n<circle class="st1" cx="50" cy="29.1" r="10.4"></circle>';
locations.appendChild(loc);
}
createLocation(0,0);

当我打开检查元素时,HTML 在那里,但 SVG 没有显示。当我尝试手动粘贴数据时,而不是通过element.innerHTML进行粘贴,它按预期工作。有谁知道为什么?

问题是用于常见HTML的document.createElement。若要创建 SVG 元素,必须使用 document.createElementNS 指定命名空间 http://www.w3.org/2000/svg。

<style type="text/css">
.st0{fill:url(#SVGID_1_);}
.st1{fill:#F4F4F4;}
</style>
<svg id="scene" viewBox="0 0 1000 1000">
<g id = "locations">
</g>
</svg>
<script>
function createLocation(px, py, video_id = "")
{
var locations = document.getElementById("locations");
var loc = document.createElementNS('http://www.w3.org/2000/svg', "g");
loc.setAttribute("id", "loc_" + video_id);
loc.innerHTML = '<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="50" y1="6.5" x2="50" y2="88.19"> <stop offset="0" style="stop-color:#F8615F"/> <stop  offset="1" style="stop-color:#C1272D"/> </linearGradient> <path class="st0" d="M69.5,40.2L69.5,40.2C50.1,74,51.3,85.1,51.1,87.2c0,0,0,0.1,0,0.1c-0.1,0.5-0.5,0.9-1,0.9s-1-0.4-1-0.9 c0,0,0-0.1,0-0.1c-0.2-2.1,0.9-13.2-18.5-47h0c-1.9-3.3-3-7.1-3-11.2C27.5,16.6,37.6,6.5,50,6.5S72.5,16.6,72.5,29 C72.5,33.1,71.4,36.9,69.5,40.2z"/> <circle class="st1" cx="50" cy="29.1" r="10.4"/>';
locations.appendChild(loc);
}
createLocation(0, 0);
</script>

最新更新