首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法通过JS渲染svg

无法通过JS渲染svg
EN

Stack Overflow用户
提问于 2020-09-03 13:34:21
回答 1查看 25关注 0票数 0

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

你能帮我理解一下这里有什么问题吗?

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

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-03 13:52:33

你的javascript很酷,你有一个CSS问题,只要给你的SVG添加一个宽度和高度,它就会显示出来。

代码语言:javascript
复制
<style>
    .svg-circleplus { stroke: green; width: 100px; height: 100px; }
</style>

代码语言:javascript
复制
//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);
代码语言:javascript
复制
svg{
  stroke: green;
  height: 100px;
  width: 100px;
}
代码语言:javascript
复制
<div id="demo"></div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63717459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档