Jas*_*n S 9 html javascript svg
我真的很困惑.我有一个静态的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>Run Code Online (Sandbox Code Playgroud)
Rob*_*son 12
使用
document.createElementNS('http://www.w3.org/2000/svg', 'svg')
Run Code Online (Sandbox Code Playgroud)
代替
document.createElement('svg')
Run Code Online (Sandbox Code Playgroud)
说明:
必须在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>.
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |