2015-10-28 62 views
0

我想在SVG下使用DOM創建標籤,我需要一些幫助。我無法弄清楚如何設置「rect」標籤的屬性。以下是HTML代碼的快照。我想創建使用DOM的相同。DOM對應的SVG元素

<svg xmlns="http://www.w3.org/2000/svg" id="svg" width ="1500" height="1500"> 
     <text x="0" y="15" fill="black">AISLE A</text> 

     <rect x=10 y=45 rx="10" ry="10" width="40" height="40" style="fill:red;stroke:black;opacity:0.5" onmouseover="this.style.stroke = 'black'; this.style['stroke-width'] = 5;" onmouseout="this.style.stroke = '#000000'; this.style['stroke-width'] = 1;"> 
      <title id="title1"> 
      Location: FP-A-02</br>Replenrate: xx%</br>PickRate: yy% 
      </title> 
      </rect> 

      <rect x=60 y=45 rx="10" ry="10" width="40" height="40" style="fill:red;stroke:black;opacity:0.5" onmouseover="this.style.stroke = 'black'; this.style['stroke-width'] = 5;" onmouseout="this.style.stroke = '#000000'; this.style['stroke-width'] = 1;"> 
      <title id="title2"> 
      Location: FP-A-02</br>Replenrate: xx%</br>PickRate: yy% 
      </title> 
      </rect> 
    <text x="0" y="15" fill="black">AISLE B</text>  
      <rect x=110 y=45 rx="10" ry="10" width="40" height="40" style="fill:red;stroke:black;opacity:0.5" onmouseover="this.style.stroke = 'black'; this.style['stroke-width'] = 5;" onmouseout="this.style.stroke = '#000000'; this.style['stroke-width'] = 1;"> 
      <title id="title3"> 
      Location: FP-A-02</br>Replenrate: xx%</br>PickRate: yy% 
      </title> 
      </rect> 

      <rect x=160 y=45 rx="10" ry="10" width="40" height="40" style="fill:red;stroke:black;opacity:0.5" onmouseover="this.style.stroke = 'black'; this.style['stroke-width'] = 5;" onmouseout="this.style.stroke = '#000000'; this.style['stroke-width'] = 1;"> 
      <title id="title4"> 
      Location: FP-A-02</br>Replenrate: xx%</br>PickRate: yy% 
      </title> 
      </rect> 
<svg> 

請注意,有2 AISLES A和B.我會創建每個AISLES內20米的矩形。手動創建它們不是一種優化的方式,因此希望使用DOM來創建元素。

+0

您可以使用D3.js,它專注於這個東西:) –

+0

不與D3舒適。是否有任何鏈接,我可以參考和做到這一點 – maverick

+0

http://chimera.labs.oreilly.com/books/1230000000345/ch03.html這整本書是真棒來源開始,但這個特定的章節將幫助你做你想要做的事情。 :) –

回答

0

您可以像處理其他DOM元素一樣處理svg標籤。例如:

// Create the SVG from scratch or get one already on your DOM 
// For sake of example, here we create one. 
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 
// Same logic for the inner tags 
var rect = document.createElementNS(svg.namespaceURI, 'rect'); 

// Once you have reference to the element, setting attributes is simple. 
// https://developer.mozilla.org/en/docs/Web/API/Element/setAttribute 
rect.setAttribute('x', 0); 
// ... 

// At the end you append all your child elements to the parent 
svg.appendChild(rect); 
// ... 
+1

SVG元素不能由createElement創建,您必須使用creatElementNS在SVG名稱空間中創建它們。 –

+0

啊是的!你是對的@RobertLongson。修復了SVG的創建元素。感謝您指出了這一點。 – 1cgonza

+0

您需要以相同的方式修復矩形。 –