尝试使用SVG标签使用JS动态创建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>发布于 2020-09-03 13:52:33
你的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>
https://stackoverflow.com/questions/63717459
复制相似问题