无法通过JS渲染SVG

时间:2020-09-03 05:34:21

标签: javascript html svg

尝试使用JS动态地使用SVG标签创建SVG减号图标。 直接在HTML正文中使用时,可以按预期呈现相同的内容。

能否请您帮助我了解这里的问题?

JS小提琴代码供参考: https://jsfiddle.net/w92ucf05/1/

<!DOCTYPE html>
<html>
<body>

<h1>My first SVG</h1>

<style>
 .svg-circleplus { stroke: green; }
</style>

<div id="demo"></div>
<!-- Expected svg -->
<svg viewbox="0 0 100 100" width="1em" height="1em" class="svg-circleplus"><circle cx="50" cy="50" r="45" style="fill: none; stroke-width: 7.5;"></circle><line x1="32.5" y1="50" x2="67.5" y2="50" style="stroke-width: 5"></line></svg>

<script>
//Script to render the smae SVG
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
    svg.setAttribute('viewbox', '0 0 100 100');
    svg.setAttribute('width', '1em');
    svg.setAttribute('height', '1em');
    svg.setAttribute("class","svg-circleplus");

var circle = document.createElementNS(svgns, 'circle');
    circle.setAttribute('cx', 50);
    circle.setAttribute('cy', 50);
    circle.setAttribute('r', 45);
    circle.setAttribute('style', 'fill: none; stroke-width: 7.5;' );
    svg.appendChild(circle);

var line = document.createElementNS(svgns, 'line');
    line.setAttribute("x1", 32.5);
    line.setAttribute("y1", 50);
    line.setAttribute("x2", 67.5);
    line.setAttribute("y2", 50);
    line.setAttribute('style', 'stroke-width: 5' );
    svg.appendChild(line);
    
document.getElementById("demo").appendChild(svg);
</script>
 
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的JavaScript很酷,您遇到了CSS问题,只需在SVG中添加宽度和高度,它就会显示出来。

<style>
    .svg-circleplus { stroke: green; width: 100px; height: 100px; }
</style>

//Script to render the smae SVG
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
    svg.setAttribute('viewbox', '0 0 100 100');
    svg.setAttribute('width', '1em');
    svg.setAttribute('height', '1em');
    svg.setAttribute("class","svg-circleplus");


var circle = document.createElementNS(svgns, 'circle');
    circle.setAttribute('cx', 50);
    circle.setAttribute('cy', 50);
    circle.setAttribute('r', 45);
    circle.setAttribute('style', 'fill: none; stroke-width: 7.5;' );
    svg.appendChild(circle);

var line = document.createElementNS(svgns, 'line');
    line.setAttribute("x1", 32.5);
    line.setAttribute("y1", 50);
    line.setAttribute("x2", 67.5);
    line.setAttribute("y2", 50);
    line.setAttribute('style', 'stroke-width: 5' );
    svg.appendChild(line);
    
document.getElementById("demo").appendChild(svg);
svg{
  stroke: green;
  height: 100px;
  width: 100px;
}
<div id="demo"></div>