2011-07-23 60 views
1

我在通過javascript操縱SVG時遇到了一些麻煩。我想通過點擊一個按鈕來增加一行的長度。我已經包括在頭標記此代碼:腳本編寫SVG時出現問題

<script type="text/javascript"> 
x=135; 
y=135; 
var container = document.getElementById("svgbox"); 
var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 


function svg() { 
mySvg.setAttribute("version", "1.2"); 
mySvg.setAttribute("baseProfile", "tiny"); 
mySvg.setAttribute("height","300px"); 
mySvg.setAttribute("width","300px"); 
container.appendChild(mySvg); 
} 

function line() { 
x=x-10; 
y=y-10; 
var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line"); 
    L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100"); 
    L1.setAttribute("x2", x); L1.setAttribute("y2", y); 
    L1.setAttribute("stroke", "#05adc7"); 
    L1.setAttribute("stroke-width", "2px"); 
    mySvg.appendChild(L1); 
} 
</script> 

這是正文:

<body onload="svg()"> 
<form> 
<input type="button" onClick="line()" /> 
</form> 
<div id="svgbox"> 
</div> 
</body> 

但是當我按一下按鈕,我得到一個錯誤,告訴我變量「容器「 一片空白。有誰知道問題是什麼?

回答

1

它的作品,如果你把行var container = document.getElementById("svgbox");在svg函數。

function svg() { 
var container = document.getElementById("svgbox"); 
mySvg.setAttribute("version", "1.2"); 
mySvg.setAttribute("baseProfile", "tiny"); 
mySvg.setAttribute("height","300px"); 
mySvg.setAttribute("width","300px"); 
container.appendChild(mySvg); 
} 

原因容器是在你的代碼null是因爲當行var container = document.getElementById("svgbox");被執行的DOM尚未加載。

您需要在DOMContentLoaded事件或window.onload事件觸發後聲明容器。

+0

這有效。謝謝您的幫助。 – dopatraman

1

這是一個常見的DOM腳本編寫的問題,對於SVG和HTML都是如此。問題在於,當JavaScript執行時,svgbox元素尚未加載。最簡單的解決方案是簡單地移動腳本標籤,使其成爲文檔中的最後一個元素。然而,這有點難看,因此大多數JavaScript庫都包含一個接受回調以在文檔加載後執行的方法。例如,如果您使用的是jQuery,那麼您的腳本標籤看起來將如下所示:

<script type="text/javascript"> 
$(document).ready(function(){ 
    x=135; 
    y=135; 
    var container = document.getElementById("svgbox"); 
    var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 


    svg = function() { 
    mySvg.setAttribute("version", "1.2"); 
    mySvg.setAttribute("baseProfile", "tiny"); 
    mySvg.setAttribute("height","300px"); 
    mySvg.setAttribute("width","300px"); 
    container.appendChild(mySvg); 
    } 

    line = function() { 
    x=x-10; 
    y=y-10; 
    var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line"); 
    L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100"); 
    L1.setAttribute("x2", x); L1.setAttribute("y2", y); 
    L1.setAttribute("stroke", "#05adc7"); 
    L1.setAttribute("stroke-width", "2px"); 
    mySvg.appendChild(L1); 
    } 
}) 
</script> 
+0

原來,最簡單的方法是將容器包含在線路功能中。感謝您的迴應。 – dopatraman

+0

另一個快速問題....我認爲我可以通過在head標籤內激發onload事件來解決代碼美學和功能性問題。但這不起作用。有誰知道爲什麼? – dopatraman

+0

你的意思是「在頭標籤中發生onload事件」? – jbeard4