2017-02-01 55 views
0

当我在DOM中已经存在的SVG元素上使用setAttribute('viewBox')时,它会正确设置(使用大写'b')。如何在使用JavaScript创建的SVG元素上设置viewBox?

当我在JavaScript中创建一个SVG元素并在其中添加'viewBox'属性。 。 。它以全部小写字母结束于DOM。

这是为什么?

document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20'); 
 

 
let svg = document.createElement('svg'), 
 
    circle = document.createElement('circle'); 
 

 
circle.setAttribute('cx', 200); 
 
circle.setAttribute('cy', 200); 
 
circle.setAttribute('r', 10); 
 
svg.setAttribute('viewBox', '190 190 20 20'); 
 
svg.appendChild(circle); 
 
document.body.appendChild(svg); 
 

 
// document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg { 
 
    border: 2px dashed #666; 
 
    width: 200px; 
 
    height: 200px; 
 
}
<p>Existing svg with dynamically added viewBox attribute:</p> 
 
<div id="circle"> 
 
    <svg> 
 
    <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" /> 
 
    </svg> 
 
</div> 
 

 
<p>Generated svg with dynamically added viewBox attribute:</p>

回答

3

你必须使用document.createElementNS("http://www.w3.org/2000/svg", "svg")代替document.createElement('svg')

document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20'); 
 

 
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"), 
 
    circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
 

 
circle.setAttribute('cx', 200); 
 
circle.setAttribute('cy', 200); 
 
circle.setAttribute('r', 10); 
 
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 
 
svg.setAttribute('viewBox', '190 190 20 20'); 
 
svg.appendChild(circle); 
 
document.body.appendChild(svg); 
 

 
// document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg { 
 
    border: 2px dashed #666; 
 
    width: 200px; 
 
    height: 200px; 
 
}
<p>Existing svg with dynamically added viewBox attribute:</p> 
 
<div id="circle"> 
 
    <svg> 
 
    <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" /> 
 
    </svg> 
 
</div> 
 

 
<p>Generated svg with dynamically added viewBox attribute:</p>

1

你没有创建摆在首位有效的SVG元素虽然。您不能使用createElement创建SVG元素(仅适用于HTML元素)。您必须使用createElementNS并提供SVG命名空间作为第一个参数。

let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), 
    circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); 
相关问题