2013-06-10 2 views
4

Я пытаюсь создать «использовать» узел с помощью javascript, но результат не может быть виден на экране, не имеет ли кто-нибудь идеи? Кстати, создание другого типа прекрасно работает, например, создание эллипса.Создание элемента использования javascript

Вот коды.

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"> 
</script> 
<script type="text/javascript"> 
//this can work 
function onEllipse(){ 
    var ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse"); 
    ellipse.setAttribute("cx", "20"); 
    ellipse.setAttribute("cy", "40"); 
    ellipse.setAttribute("rx", "20"); 
    ellipse.setAttribute("ry", "10"); 
    ellipse.setAttributeNS(null,'style','visibility:visible;fill:green'); 
    svg.appendChild(ellipse); 
} 

//this **WON"T** work, the referenced node "#circle1" is alredy in the "defs" 
function onUse(){ 
    var xmlns = "http://www.w3.org/2000/svg"; 
    var svgns = 'http://www.w3.org/2000/xlink/namespace/'; 
    var Node = document.createElementNS(xmlns,'use'); 
    Node.setAttributeNS(null,'id','abcd'); 
    Node.setAttributeNS(null,'x','200'); 
    Node.setAttributeNS(null,'y','200'); 
    Node.setAttributeNS(null,'style','visibility:visible;fill:green'); 
    Node.setAttributeNS(svgns,'xlink:href','#circle1'); 
    svg.appendChild(Node); 
} 


var svg; 
$(document).ready(function(){ 
    svg = document.getElementsByTagName('svg')[0]; 
}); 
</script> 
</head> 

<body> 
    <div id="left-toolbar" style="float:left;border:1px solid #DDDDDD;overflow:auto"> 
     <input type='button' onclick='onEllipse()' value='ellipse' /><br /> 
     <input type='button' onclick='onUse()' value='use' /><br /> 
    </div> 

    <div id="workarea" style="float:left;border:1px solid #DDDDDD;margin:0px 20px 0px 20px;overflow:auto"> 
     <svg width="1280px" height="720px" viewBox="0 0 1280 720" xmlns="http://www.w3.org/2000/svg"> 
      <defs> 
       <circle id="circle1" cx="35" cy="20" r="20" style="stroke: black; fill: none;" /> 
      </defs> 
      <!--use x="100" y="100" xlink:href = "#circle1"/--> 
     </svg> 
    </div> 
</body> 
</html> 

ответ

4

XLink пространство имен http://www.w3.org/1999/xlink так что вы хотите

var svgns = 'http://www.w3.org/1999/xlink'; 

Хотя вызова XLINK svgns пространства имен будет казаться мне быть источником путаницы.

1

Использование:

var xlink = 'http://www.w3.org/1999/xlink'; 
Node.setAttributeNS(xlink,'href','#circle1'); 

вместо:

var svgns = 'http://www.w3.org/2000/xlink/namespace/'; 
Node.setAttributeNS(svgns,'xlink:href','#circle1'); 
Смежные вопросы