我真的很困惑.我有一个静态的SVG元素显示正常,但是当我从
Javascript添加一个相同的元素时,它不会显示.为什么是这样??
@H_404_2@<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>
解决方法
使用
@H_404_2@document.createElementNS('http://www.w3.org/2000/svg','svg')
代替
@H_404_2@document.createElement('svg')说明:
必须在SVG名称空间中创建SVG元素,因此不能由createElement创建,而必须使用createElementNS将SVG名称空间作为第一个参数.
createElement基本上创建了名为svg和circle而不是SVG元素的html元素.
text / html实际上没有名称空间,所以HTML解析器在遇到< svg>时会神奇地切换到SVG名称空间.元件.如果您将mime类型更改为某个XML命名空间,例如http://www.w3.org/1999/xhtml/然后你需要根< html>上的xmlns属性元素以及< svg>元件.
@H_404_2@<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); console.log(svg); var c = document.createElementNS('http://www.w3.org/2000/svg','circle'); c.setAttribute('cx','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>