我真的很困惑。我有一个显示良好的静态 SVG 元素,但是当我从 Javascript 添加相同的元素时,它不显示。这是为什么??
<html>
<head>
<script type="text/javascript">
function doit()
{
var svgdiv = document.getElementById('svg1');
for (var k = 1; k < 3; ++k)
{
var svg = document.createElement('svg');
svg.setAttribute('width',100);
svg.setAttribute('height',100);
console.log(svg);
var c = document.createElement('circle');
c.setAttribute('cx',50);
c.setAttribute('cy',50);
c.setAttribute('r',40);
c.setAttribute('stroke','green');
c.setAttribute('stroke-width',4);
c.setAttribute('fill','yellow');
svg.appendChild(c);
svgdiv.appendChild(svg);
}
}
window.onload = doit;
</script>
</head>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<div id="svg1"></div>
</body>
</html>
最佳答案
使用
document.createElementNS('http://www.w3.org/2000/svg', 'svg')
代替
document.createElement('svg')
解释:
SVG 元素必须在 SVG 命名空间中创建,因此不能由 createElement 创建,而必须使用 createElementNS 提供 SVG 命名空间作为第一个参数。
createElement 基本上创建名为 svg 和 circle 的 html 元素,而不是 SVG 元素。
text/html 并没有真正的命名空间,因此 HTML 解析器在遇到 <svg>
时神奇地切换到 SVG 命名空间。元素。如果您将 mime 类型更改为某个 XML namespace ,例如http://www.w3.org/1999/xhtml/那么你需要根上的 xmlns 属性 <html>
元素,也在 <svg>
上元素。
<html>
<head>
<script type="text/javascript">
function doit()
{
var svgdiv = document.getElementById('svg1');
for (var k = 1; k < 3; ++k)
{
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width',100);
svg.setAttribute('height',100);
console.log(svg);
var c = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
c.setAttribute('cx',50);
c.setAttribute('cy',50);
c.setAttribute('r',40);
c.setAttribute('stroke','green');
c.setAttribute('stroke-width',4);
c.setAttribute('fill','yellow');
svg.appendChild(c);
svgdiv.appendChild(svg);
}
}
window.onload = doit;
</script>
</head>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<div id="svg1"></div>
</body>
</html>
关于javascript - Javascript 添加的动态 svg 元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489143/